[英]How to implement type declaration with generics?
如何定义一个函数,该函数是包含泛型的类型声明的实现?
这就是我的意思:
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
能做到吗?
/ edit没关系,它实际上可以在Playground中使用 。 猜猜这是编译器版本问题
这有效:
declare type BaseFactory = <T extends Base>() => T;
let subFactory: BaseFactory = (): Sub => new Sub();
let a = subFactory<Sub>(); // type of a is Sub
( 操场上的代码 )
但我会这样做:
declare type BaseFactory<T extends Base> = () => T;
let subFactory: BaseFactory<Sub> = (): Sub => new Sub();
let a = subFactory(); // type of a is Sub
( 操场上的代码 )
如果您使用的打字稿> = 2.3,则可以使用默认的泛型:
declare type BaseFactory<T extends Base = Base> = () => T;
然后,您无需在所有地方都指定T
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.