[英]How to extract discriminator from tuple of classes in Typescript
給定以下代碼:
abstract class Fruit {
abstract readonly fruitType: string;
}
class Banana extends Fruit {
readonly fruitType = "banana";
length = 2;
color = "yellow";
}
class Pear extends Fruit {
readonly fruitType = "pear";
roundness = "very round";
}
class Apple extends Fruit {
readonly fruitType = "apple";
fallOfMan = true;
hasWorms = true;
}
const fruits = [Banana, Pear, Apple] as const;
export type Fruits = typeof fruits[number];
export type FruitTypes = Fruits["fruitType"]; // This should be "banana" | "pear" | "apple"
為什么我無法得到正確的鑒別器聯合?
當我回答時,您的問題是:
// Original code in question
export type FruitTypes = Fruits["name"];
Fruits
是構造函數Banana
、 Pear
和Apple
的類型的聯合——實際的函數,而不是它們產生的實例的類型。 (構造函數) function 的name
始終是一個字符串,這就是你最初得到string
的原因。 更新后的問題現在出現錯誤,因為這些構造函數沒有fruitType
成員。
您可以使用InstanceType
獲取您想要的聯合來獲取那些構造函數創建的實例的類型,並使用"fruitType"
來訪問這些實例的fruitType
成員的類型:
export type FruitTypes = InstanceType<Fruits>["fruitType"];
// −−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^−−−−−−^^^^^^^^^^^^^^
或者你可以更直接:
export type FruitTypes = (Banana | Pear | Apple)["fruitType"];
...但我猜您出於維護原因試圖避免重復該列表(在上面還有fruits
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.