Benny Bottema
Benny Bottema

Reputation: 11493

How to implement type declaration with generics?

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

Answers (1)

Nitzan Tomer
Nitzan Tomer

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

(code in playground)

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

(code in playground)


Edit

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

Related Questions