Typescript: Class as parameter?

Created on 28 Nov 2015  ·  4Comments  ·  Source: microsoft/TypeScript

Can we do something like

class Serializable {
   public toString() {} 
}
class Test extends Serializable {
    public key:string
}

test(Test);
function test(klass: Class<? extends Serializable>) {
    var obj = new klass();
    obj.toString()
}
Question

Most helpful comment

You might want something like

function tests<T extends Serializable>(constructorFn: new () => T) {
    var obj = new constructorFn()
    obj.toString()
}

Where the type new () => T means that you can call a value of that type and get a T out of it.

All 4 comments

You might want something like

function tests<T extends Serializable>(constructorFn: new () => T) {
    var obj = new constructorFn()
    obj.toString()
}

Where the type new () => T means that you can call a value of that type and get a T out of it.

But it also allows to pass anything to it (like some class did not extend from serializable) .

That's because your implementation of Serializable just requires toString(): string, which every type has by default anyway. That means every constructor function is structurally compatible with Serializable. If the method's name was something else, or you added an extra property on Serializable (like __serializable: any), then you'd get an error.

It does not seem work with generics.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

blendsdk picture blendsdk  ·  3Comments

weswigham picture weswigham  ·  3Comments

uber5001 picture uber5001  ·  3Comments

fwanicka picture fwanicka  ·  3Comments

bgrieder picture bgrieder  ·  3Comments