[英]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.