考虑一下,我们有一个联合类型来表示三个不同的字符串值之一。
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错误?