【发布时间】:2021-07-27 11:18:27
【问题描述】:
给定以下代码:
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"
为什么我无法得到正确的鉴别器联合?
【问题讨论】:
-
你的意思是
Fruits["fruitType"]吗? -
@BenWainwright - 这给出了一个错误:tsplay.dev/Wyv7bw。
Fruits是typeof Banana | typeof Pear | typeof Apple(构造函数类型),而不是Banana | Pear | Apple。 -
我并不是说它是解决方案,但我没有将“名称”视为您代码中任何地方的属性...
-
@BenWainwright - 它们是构造函数。函数有一个
name属性。 (我不是 OP。:-)) -
@mikeysee -
fruits和Fruits的类型真的是你想要的吗?构造函数(及其类型)?
标签: typescript types tuples