鉴于以下代码:
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
-实际的功能,而不是类型它们所产生的实例。name
(constructor) 函数的of 始终是一个字符串,这就是为什么最初您得到string
. 更新后的问题现在出现错误,因为这些构造函数没有fruitType
成员。
您可以获取想要使用的联合InstanceType
来获取这些构造函数创建的实例的类型,并"fruitType"
访问fruitType
这些实例的成员的类型:
export type FruitTypes = InstanceType<Fruits>["fruitType"];
// −−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^−−−−−−^^^^^^^^^^^^^^
或者你可以更直接:
export type FruitTypes = (Banana | Pear | Apple)["fruitType"];
...但我猜你是fruits
因为维护原因试图避免重复该列表(在上面和)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句