【发布时间】:2021-10-07 19:12:56
【问题描述】:
如何制作类示例以根据animalType实例值检查推断config类型:
enum Animal {
BIRD = 'bird',
DOG = 'dog',
}
type Base = {
id: number
}
// Object example
type Smth = Base &
(
| {
animalType: Animal.BIRD;
config: number;
}
| {
animalType: Animal.DOG;
config: string;
}
);
// type guards working
const smthObj: Smth = {
id: 1,
animalType: Animal.BIRD,
config: 1
};
// should be error
const smthObj2: Smth = {
id: 1,
animalType: Animal.BIRD,
config: 'x'
};
if (smthObj.animalType === Animal.BIRD) {
smthObj.config = 1;
smthObj.config = 'x'; // should be error
}
// How to make it work the same for class?
class myClass {
id: number;
animalType: Animal;
// this should be based on Animal type
// number for bird and string for dog
config: number | string;
constructor(id: number, animalType: Animal, config: number | string) {
this.id = id;
this.animalType = animalType;
this.config = config
}
}
const smthClass: myClass = 1 as any
// I need to make only this check to work
if (smthClass.animalType === Animal.BIRD) {
smthClass.config = 1;
smthClass.config = 'x'; // should be error
}
【问题讨论】:
-
@Behemoth 滚动到底部
smthClass.config = 'x'; // should be error -
这可能很有趣:stackoverflow.com/q/56085306
-
您是否考虑过创建与您拥有的动物一样多的子类(例如,一个用于 Bird,另一个用于 Dog 等),然后分别在配置上设置类型?看来您正在寻找工厂,但试图通过联合在类级别上实现;由于上面链接的答案中描述的原因,这将不起作用。
-
@raina77ow 这是一个复杂的反对数据库模型,具有多种类型和方法,只有这个属性可以是两种类型之一,所以我希望 ts 可以以某种方式在 if 块中推断它,例如对象示例 :(会更容易,然后只检查 config 是 if 块中的数字还是字符串
标签: typescript