【发布时间】:2023-03-10 15:35:01
【问题描述】:
假设我们有一个联合类型,它代表三个不同的字符串值之一。
type Animal = 'bird' | 'cat' | 'dog';
现在我想创建一只狗并检查它是什么动物来产生正确的噪音。
let oscar: Animal = 'dog';
switch (oscar) {
case 'bird':
console.log('tweet');
break;
case 'cat':
console.log('meow');
break;
case 'dog':
console.log('bark');
break;
}
此代码将导致 TypeScript 错误:Type '"bird"' is not comparable to type '"dog"'.ts(2678)(与 cat 类似)。但是,如果我在变量 oscar 上使用显式类型转换,则它可以正常工作:
switch (oscar as Animal) {
case 'bird':
...
case 'cat':
...
case 'dog':
...
}
如果我对 oscar 使用显式值,您能否解释一下为什么前两个 switch 语句会失败?
如果我将 Oscar 声明为常量,我可以理解错误:const oscar = 'dog';,因为在这种情况下,它永远是一只狗,没有别的。但是,试想一下,如果巫师施展某种咒语,奥斯卡可能会变成一只猫:
let oscar: Animal = 'dog';
while(true) {
switch (oscar) {
case 'bird':
...
case 'cat':
...
case 'dog':
console.log('bark');
// here comes the wizard
if(wizard.performsSpell('makeOscarBecomeACat')) {
oscar = 'cat'; // that should be valid, because oscar is of type Animal
}
break;
}
}
我是否误解了变量oscar 的赋值,或者这仅仅是一个 TypeScript 错误?
【问题讨论】:
标签: javascript typescript switch-statement union-types