如何用泛型实现类型声明?

时间:2017-06-05 13:16:40

标签: generics typescript

如何定义一个函数,该函数是包含泛型的类型声明的实现?

这就是我的意思:

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

不幸的是,这会产生以下错误:

  

Sub is not assignable to parameter of type Base

可以这样做吗?

/编辑nevermind,它actually works in Playground。猜猜这是编译器版本问题

1 个答案:

答案 0 :(得分:2)

这有效:

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

但我这样做:

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

修改

如果你使用的是typescript&gt; = 2.3,那么你可以使用默认的泛型:

declare type BaseFactory<T extends Base = Base> = () => T;

然后你不需要在任何地方指定T