[英]TypeScript generic class that creates instances of its type variable's class?
我熟悉TypeScript中的泛型類,其中可以使用關聯的類型變量定義類,然后具有特定類型的實例可以操作並返回該類型的值。
問題:我想要一個創建類型變量實例的泛型類。 例如:
class Thing {
thingProp: string;
}
class ThingOne extends Thing {
thingOneProp: string;
}
class ThingTwo extends Thing {
thingTwoProp: string;
}
class Maker<T extends Thing> {
make(): T {
return new T();
// ^--- " // <- "error TS2304: Cannot find name 'T'""
}
}
let thingOneMaker = new Maker<ThingOne>();
let thingOne: ThingOne = thingOneMaker.make();
let thingTwoMaker = new Maker<ThingTwo>();
let thingTwo: ThingTwo = thingTwoMaker.make();
let thingError: ThingOne = thingTwoMaker.make();
// ^--- "error TS2322: Type 'ThingTwo' is not assignable to type 'ThingOne'"
這幾乎似乎有效。 編譯器生成代碼,最后一行的錯誤表明TypeScript了解thingTwoMaker.make()
應返回的類型。
但是, return new T();
出錯return new T();
表明TypeScript不理解我正在嘗試創建類型變量的類的實例,並且生成的JavaScript確認它:
var Maker = (function () {
function Maker() {
}
Maker.prototype.make = function () {
return new T(); // <- "error TS2304: Cannot find name 'T'"
};
return Maker;
}());
並且,毫不奇怪,使用Node.js運行生成的JavaScript會產生ReferenceError: T is not defined
錯誤。
如何創建一個泛型類,其實例可以創建類型變量類的實例? (使用TypeScript 2.0.10測試。)
不知何故,你需要為Maker
類提供你想要它的類型的構造函數,以便它有一個值來調用new
。
我想說一個好的選擇是將類構造函數作為參數傳遞給Maker
的構造函數。 這將允許它構造該類的實例,並且它將自動推斷它正在構建的類型,因此您不必再手動注釋泛型類型。
也許是這樣的:
class Maker<T extends Thing> {
private ctor: {new(): T};
constructor(ctor: {new(): T}) {
this.ctor = ctor;
}
make(): T {
return new this.ctor();
}
}
然后,您可以將正確的類構造函數傳遞給每種Maker
,並自動推斷類型:
let thingOneMaker = new Maker(ThingOne);
let thingOne: ThingOne = thingOneMaker.make();
let thingTwoMaker = new Maker(ThingTwo);
let thingTwo: ThingTwo = thingTwoMaker.make();
// Still an error.
let thingError: ThingOne = thingTwoMaker.make();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.