Getting error can not compile module unless --module flag is provided. so not able to create instance of this class in another ts file - javascript

export module FilterBar {
export class Filter {
objData: any;
distinctAreas: string[];
distinctRegions: string[];
distinctSubRegions: string[];
distinctAreasApplied: string[];
distinctRegionsApplied: string[];
distinctSubRegionsApplied: string[];
call = 0;
static selectedFilterData: any;
}
I want to create an object of this class in another typescript file. For that I am using export to module but I am getting the mentioned error.

Related

Typescript: es6 import type definition (.d.ts) from node_modules subfolder

I have a npm package that has the following type definitions (simplified):
./node_modules/ag-grid-react/main.d.ts
export declare class AgGridReact extends Component<AgGridReactProps, {}> {}
./node_modules/ag-grid-react/lib/agGridReact.d.ts
export declare class AgGridReact extends Component<AgGridReactProps, {}> {
gridOptions: GridOptions;
api: GridApi | null;
columnApi: ColumnApi;
}
I am using the component in my react component like this:
import { AgGridReact } from 'ag-grid-react'
const HelpRequests= () => {
const grid = useRef<AgGridReact>(null)
if (grid.current) console.log(grid.current.columnApi)
return (<AgGridReact ref={grid}/>)
}
The Problem:
Typescript does complain that there is no columnApi. It seems it sadly picks the wrong type from the main.d.ts
I found that I can import the type from the agGridReact.d.ts directly and use it like this:
import {AgGridReact as AgGridReactType} from 'ag-grid-react/lib/agGridReact'
...
const grid = useRef<AgGridReactType>(null)
Question:
Is this the correct way to address this issue? Will typescript be smart enough not to import the ./node_modules/ag-grid-react/lib/agGridReact.ts file which could cause my bundle size to go up?
I've searched a lot but could not find anything about importing types only from node_modules subfolders.
I will try to answer this:
Let's assume there is an xyz library and it has these files:
xyz/lib/main.ts:
export const test = 1000
and
xyz/main.ts:
export * from './lib/main.ts'
export const test = 'foo bar'
And I would like to use xyz in my app.ts, and I am aware of only its main.ts file as I think it is the main file which exports everything from library. So I am most likely to do:
app.ts:
import { test } from './xyz/main'
console.debug(test) // it will print 'foo bar'
Now, somebody goes and comment this line in the library:
xyz/main.ts:
export * from './lib/main.ts'
// export const test = 'foo bar'
Now, what will be printed by my app.ts? It will print 1000.
The same thing is happening there with ag-grid-react. It (ag-grid-react/main.d.ts) is overriding the apparently correct (better) class declaration present in ag-grid-react/lib/agGridReact.d.ts. And it is perfectly fine to import from inner path.
main.d.ts:
export * from './lib/agGridReact'; // it is exporting from innner path too
export declare class AgGridColumn extends Component<AgGridColumnProps | AgGridColumnGroupProps, {}> { // and overriding here at the same time
}
agGridReact.d.ts:
export declare class AgGridReact extends Component<AgGridReactProps, {}> {
props: any;
state: any;
static propTypes: any;
gridOptions: GridOptions;
changeDetectionService: ChangeDetectionService;
api: GridApi | null;
columnApi: ColumnApi;
portals: ReactPortal[];
hasPendingPortalUpdate: boolean;
destroyed: boolean;
protected eGridDiv: HTMLElement;
private static MAX_COMPONENT_CREATION_TIME;
constructor(props: any, state: any);
render(): React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)>) | (new (props: any) => React.Component<any, any, any>)>;
createStyleForDiv(): any;
componentDidMount(): void;
waitForInstance(reactComponent: ReactComponent, resolve: (value: any) => void, runningTime?: number): void;
mountReactPortal(portal: ReactPortal, reactComponent: ReactComponent, resolve: (value: any) => void): void;
batchUpdate(callback?: any): any;
destroyPortal(portal: ReactPortal): void;
private getStrategyTypeForProp;
shouldComponentUpdate(nextProps: any): boolean;
componentDidUpdate(prevProps: any): void;
processPropsChanges(prevProps: any, nextProps: any): void;
private extractDeclarativeColDefChanges;
private extractGridPropertyChanges;
componentWillUnmount(): void;
isDisableStaticMarkup(): boolean;
}
I can't exactly say why ag-grid did this. I found this looking at the typing files. I may be incorrect too.

How to declare a JS mixin for vue?

I'm writting a vue project with typescript and I want to use a mixin from thrid-part library which write by javascript, how to write a .d.ts to make ts can find function define in the mixin?
I tried this way and it not working:
// common.d.ts
declare module 'thrid-part-lib' {
import { VueClass } from 'vue-class-component/lib/declarations';
export interface SomeMixin<T> extends VueClass<T> {
refresh(): Promise<void>;
}
}
// index.ts
import { Component, Mixins } from 'vue-property-decorator';
import { SomeMixin } from 'thrid-part-lib';
#Component
export default class Index extends Mixins(SomeMixin) {
public foo() {
this.refresh(); // 'refresh' is not define.
}
}
You can augment a third party mixin with creating a file like vuelidate-error-extractor.d.ts:
declare module 'vuelidate-error-extractor' {
import { ValidationRule } from 'vuelidate/lib/validators';
// eslint-disable-next-line #typescript-eslint/class-name-casing
export class singleErrorExtractorMixin extends Vue {
readonly events: any;
readonly name: string;
readonly isValid: boolean;
readonly hasErrors: boolean;
readonly preferredValidator: ValidationRule;
}
}
This augments this JS file, but in an incomplete manner.
This is documented in "Augmenting Types for Use with Plugins".
Put this in a .d.ts file in your project to add a refresh() mixin method to components:
// 1. Make sure to import 'vue' before declaring augmented types
import Vue from 'vue'
// 2. Specify a file with the types you want to augment
// Vue has the constructor type in types/vue.d.ts
declare module 'vue/types/vue' {
// 3. Declare augmentation for Vue
interface Vue {
refresh(): void;
}
}

how to convert to import/export module's syntax by TypeScript global module

I want to convert older project's typescript code, for example:
// dataService.ts
module ProjectNs.Models {
export class DataService {
props1: string;
constructor(
private service: ProjectNs.Service.MyInjectService
) { }
}
}
it's equal global variable's method. now, I want to use webpack, and like es6 module syntax. for example:
// dataService.ts
export class DataService {
props1: string;
constructor(
private service: ProjectNs.Service.MyInjectService
) { }
}
// main.ts
import {DataService} from './dataService';
class Main {
}
There are so many TypeScript File, so, Is there any tool for batch conversion?

How to call classes and function in type definition file?

I'm newbe in typescript and trying to use type definition file with typescript 2.2, (I'm using typescriptlang.org but can't get answer)I have the following type definition file
export as namespace mydefinition;
export namespace mynamespace {
interface Myinterface {
width: number;
height: number;
}
class MyClass {
constructor(attributes?: any);
addCell(cell: Cell): this;
}
}
I'm using the following line to import file and it success
import { mydefinition } from 'definitionfile';
How can I call the classes and function of this definition file?
Looks good to me. You are just missing the initialization of your myclass.
import { mydefinition } from './definitionfile';
export class classA implements mydefinition.Myinterface {
width: number;
height: number;
constructor() {
var test = new mydefinition.MyClass();
test.addCell("attr");
}
}

Typescript definition file for javascript class throws runtime error

I am using Visual Studio 2015 IDE.
I have a file Messaging.d.ts. It defines a couple of classes written in javascript. The definition in the TS file is written as follows:
declare module 'Messaging' {
export default class DisplayMessageManager {
AddMainMessage(message: string, alertCssClass: string): void;
DontShowTipAgain(alertID: string): void;
CloseTip(alertID: string, showAlertTime: number): void;
TogglePanelDirty(panelID: string, isDirty: boolean, originalState: string): void;
}
}
declare module 'MessagingConstants' {
export default class Constants {
//Bootstrap Alert Classes
bsSuccess: string;
bsWarning: string;
bsDanger: string;
bsInfo: string;
bsDefault: string;
bsPrimary: string;
}
}
When I import this in my app.ts file (in the same folder) I use:
import DisplayMessageManager from 'Messaging';
import Constants from 'MessagingConstants';
and then:
messageManager: DisplayMessageManager = new DisplayMessageManager();
messageConstants: Constants = new Constants();
later I use:
this.messageManager.AddMainMessage('test', this.messageConstants.bsSuccess);
This all compiles correctly. However, when I run the code the error in the console tells me that it cannot find the file 'Messaging.js'. I did not think that a typescript definition file needed to compile into a javascript file. What am I doing wrong to get these external javascript classes to work?
Since you're using non-relative paths (i.e. "Messaging" instead of "./Messaging"), if you're using CommonJS, this means you should have a node_modules/Messaging/ and node_modules/MessagingConstants/.
I'm not sure if that's actually what you want. What you may've meant to do is create the following two declaration files to reflect the exact shape of your local .js files
Messaging.d.ts:
export default class DisplayMessageManager {
AddMainMessage(message: string, alertCssClass: string): void;
DontShowTipAgain(alertID: string): void;
CloseTip(alertID: string, showAlertTime: number): void;
TogglePanelDirty(panelID: string, isDirty: boolean, originalState: string): void;
}
MessagingConstants.d.ts:
export default class Constants {
//Bootstrap Alert Classes
bsSuccess: string;
bsWarning: string;
bsDanger: string;
bsInfo: string;
bsDefault: string;
bsPrimary: string;
}
And then include them like so:
import DisplayMessageManager from './Messaging';
import Constants from './MessagingConstants';

Categories

Resources