Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript 1.5 exporting/importing classes

Tags:

typescript

It might be a misunderstanding from my part. In Typescript 1.4 we use to export import classes, but when I updated my code to typescript 1.5 the behavior changed.

Here is how it worked in TS 1.4

LanguageForm.ts

import AbstractForm = require('../components/AbstractForm');

class LanguageForm extends AbstractForm {
    buildPanel(){

    }
}
export = LanguageForm;

From my understanding in TS 1.5 the syntaxt needs to be modify to :

import AbstractForm from '../components/AbstractForm';
export default class LanguageForm extends AbstractForm {
    buildPanel(){

    }
}

Whith TS1.4 I could simply do a call on new in order for it to work in a dynamic setting :

require(["LanguageForm"], (Form) => {
    new Form()
});

now in TS 1.5 I need to do :

require(["LanguageForm"], (Form) => {
    new Form.default()
});

My question In all the example I found the documentation was exporting/importing modules. Is that the way to export/import classes? Can I get rid of the .default?

like image 852
David Laberge Avatar asked Jul 28 '15 14:07

David Laberge


People also ask

How do I export a TypeScript class?

Use named exports to export multiple classes in TypeScript, e.g. export class A {} and export class B {} . The exported classes can be imported by using a named import as import {A, B} from './another-file' . You can have as many named exports as necessary in a file.

Does TypeScript support Commonjs?

Yes, you can use it in a same manner that you would use it in Javascript. Typescript is superset of Javascript, all things possible in Javascript are also possible in Typescript.

Can I use module exports in TypeScript?

In TypeScript, just as in ECMAScript 2015, any file containing a top-level import or export is considered a module. Conversely, a file without any top-level import or export declarations is treated as a script whose contents are available in the global scope (and therefore to modules as well).


1 Answers

In all the example I found the documentation was exporting/importing modules. Is that the way to export/import classes

Don't use export =. Instead export:

export class LanguageForm extends AbstractForm {
    buildPanel(){

    }
}

And import:

import {LanguageForm} from '../components/LanguageForm';
like image 148
basarat Avatar answered Oct 29 '22 22:10

basarat