Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

interface + new vs class + constructor in TypeScript

Tags:

typescript

In a *.d.ts file what is the difference between:

declare module "m1" {
}

and

declare module m1 {
}

?

Also what is the difference between:

declare module "m1" {
    export class c1 {
        constructor(value: string);
    }
} 

and

declare module "m1" {
    export interface c1 {
        new(value: string);
    }
}
like image 426
Trident D'Gao Avatar asked Nov 21 '25 18:11

Trident D'Gao


1 Answers

The only different with module names in quotes is that they can only be used in ambient declarations. When you use a quoted name, you are describing a module that would be module-loaded (using require).

The difference between the class and the interface is that with the class you will be allowed to create new instances directly:

var instance = new m1.c1('val');

With the interface, you would need to additionally supply a variable that was typed to the interface in order to create a new one:

declare module m1 {
    interface c1 {
        new(value: string);
    }

    var example: m1.c1;
} 

// Not allowed
// var instance = new m1.c1('val');

// Allowed
var instance = new m1.example('val');

Using new m1.c1('val') will get you the error:

The property 'c1' does not exist on value of type 'typeof m1'.

like image 96
Fenton Avatar answered Nov 24 '25 20:11

Fenton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!