我想根據給工廠方法的實體引數來創建實體。我能夠使用多載撰寫以下代碼。如何使用TypeScript的泛型來表達呢?
uj5u.com熱心網友回復: 你可以將 這對你的例子呼叫的行為是一樣的: 不幸的是,你的實作將不會被視為型別安全;型別 我不打算繼續討論為什么會發生這種情況,我只想引導您到microsoft/TypeScript#33912,即相關的公開功能請求,以改進對實作回傳條件型別的通用函式的語言支持。 目前,您需要做一些類似于型別斷言的事情: 或者等價地,一個單一的呼叫簽名overload: 我知道你說你不想要多載,但這通常是我的解決方案,因為到處添加型別斷言是比較混亂和繁瑣的。
標籤: 上一篇:如何在其他片段中重復使用一個布局
class Car {
品牌 = 'Skoda'。
}
class Human {
name = 'Jan';
}
class Garage {
lots = 5;
}
class House {
floors = 2;
}
class NotAllowed {
anything = 'anything';
}
class Selection {
pick(what: Car) 。Garage;
pick(what: Human)。房子。
pick(what: any) : any {
if (what instanceof Car) {
return new Garage()。
} else if (what instanceof Human) {
return new House()。
} else {
throw Error('not supported')
}
}
}
const selection = new Selection() 。
selection.pick(new Car()).lots; //compiler successfully autocomplete
selection.pick(new Human()).floors //編譯器成功自動完成
selection.pick(new NotAllowed()); //編譯器錯誤。
pick()的呼叫簽名改為通用方法,其引數為通用型別受限,以union你所期望的不同輸入型別,并且其回傳型別是一個條件型別,根據輸入型別來選擇輸出型別: declare class Selection{
pick<T extends Car | Human>(what: T) 。T extends Car ? 車庫 : 房屋。
const selection = new Selection();
selection.pick(new Car()).lots; //compiler successfully autocomplete
selection.pick(new Human()).floors //編譯器成功自動完成
selection.pick(new NotAllowed()); //編譯器錯誤。
T將在pick()的主體中被unspecified,因此編譯器不會也不能驗證T是否可以被賦值給Car,即使what instanceof Car是真的:pick< T extends Car | Human>(what: T): T extends Car ? 車庫 : 房屋 {
if (what instanceof Car) {
return new Garage(); /span> error!
//Type 'Garage' is not assignable to type 'T extends Car ? Garage : House'
} else if (what instanceof Human) {
return new House(); // error!
//Type 'House' is not assignable to type 'T extends Car ? Garage : House'.
} else {
throw Error('not supported')
}
}
pick< T extends Car | Human>(what: T): T extends Car ? 車庫 : 房屋 {
if (what instanceof Car) {
return new Garage() as T extends Car ? 車庫 : 房屋。
} else if (what instanceof Human) {
return new House () as T extends Car ? 車庫 : 房屋。
} else {
throw Error('not supported')
}
}
pick< T extends Car | Human>(what: T): T extends Car ? 車庫 : 房屋。
pick(what: Car | Human) {
if (what instanceof Car) {
return new Garage()。
} else if (what instanceof Human) {
return new House()。
} else {
throw Error('not supported')
}
}
