Reputation: 11493
How can I define a function which is an implementation of a type declaration that includes generics?
Here's what I mean:
abstract class Base {}
class Sub extends Base {}
declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = <Sub>():Sub => new Sub();
console.debug(subFactory()); // expect instance of Sub
Unfortunately, this produces the following error:
Sub is not assignable to parameter of type Base
Can this be done?
/edit nevermind, it actually works in Playground. Guess it's a compiler version issue
Upvotes: 1
Views: 47
Reputation: 164139
This works:
declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = (): Sub => new Sub();
let a = subFactory<Sub>(); // type of a is Sub
But I'd do it like this:
declare type BaseFactory<T extends Base> = () => T;
let subFactory: BaseFactory<Sub> = (): Sub => new Sub();
let a = subFactory(); // type of a is Sub
If you're using typescript >= 2.3 then you can use default generics:
declare type BaseFactory<T extends Base = Base> = () => T;
And then you don't need to specify T
everywhere.
Upvotes: 2