1

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

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The problem with the second version is now you have to declare T everywhere BaseFactory is used as property or parameter, where as with the first version, T is only needed when actually invoking the function.
Check my revised answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.