TypeScript constructor in interface -


the typescript doc says following code:

interface clockconstructor {     new (hour: number, minute: number): clockinterface; } interface clockinterface {     tick(); }  function createclock(ctor: clockconstructor, hour: number, minute: number): clockinterface {     return new ctor(hour, minute); }  class digitalclock implements clockinterface {     constructor(h: number, m: number) { }     tick() {         console.log("beep beep");     } } class analogclock implements clockinterface {     constructor(h: number, m: number) { }     tick() {         console.log("tick tock");     } }  let digital = createclock(digitalclock, 12, 17); let analog = createclock(analogclock, 7, 32); 

...

because createclock’s first parameter of type clockconstructor, in createclock(analogclock, 7, 32), checks analogclock has correct constructor signature.

however, compiling same code without constructor, not throw error can see here

why that? missing anything?

not having constructor in ts class still create 1 in compiled js:

class digitalclock implements clockinterface {     tick() {         console.log("beep beep");     } } 

compiles into:

var digitalclock = (function () {     function digitalclock() {     }     digitalclock.prototype.tick = function () {         console.log("beep beep");     };     return digitalclock; }()); 

so there's constructor there doesn't receive arguments, in javascript can still call function doesn't declare arguments arguments:

function fn() {     console.log(arguments); } fn(1, 2, 3); // [1, 2, 3] 

in case typescript complain calling fn arguments.
ok:

type myfunction = { (a: number, b: number, c: number): void }  (fn myfunction)(1, 2, 3); 

i guess compiler trusts you know doing, ctor exists , can in fact arguments arguments object.

this how ever fail:

class analogclock implements clockinterface {     constructor(str: string) {}     tick() {         console.log("tick tock");     } } let analog = createclock(analogclock, 7, 32); 

because there's different ctor signature.


Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -