简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM