问题描述
当switch的条件为true时ts没有校验case中的条件
有问题的代码
type Pos = { index: number; deviation: string; }| null |false;
const getPos=(type:number):Pos=>{
switch (type) {
case 1:
return { index: 1, deviation: '1'};
case 2:
return null;
default:
return false;
}
}
const pos:Pos=getPos(1);
let index=1;
let deviation='deviation';
switch (true) {
case !!pos && !!pos.deviation:
index = pos.index; // 此处报错
deviation = pos.deviation;// 此处报错
console.log(index);
console.log(deviation);
break;
case pos !== false:
console.log('pos');
break;
default:
break;
}
问题截图
我已经在case里面判断了pos
,确认了pos
一定为对象的时候才会走下面的逻辑,不明白为什么会报错
,但是当我们不用switch
而是用if...else
的时候就不会有这个问题,所以猜测typescript
在校验的时候可能没有去执行case里面的代码
解决方案
两种方案
- 使用
if...else
改写, - 在
switch
里面在加一个if...else
方案二 编码实战
type Pos = { index: number; deviation: string; }| null |false;
const getPos=(type:number):Pos=>{
switch (type) {
case 1:
return { index: 1, deviation: '1'};
case 2:
return null;
default:
return false;
}
}
const pos:Pos=getPos(1);
let index=1;
let deviation='deviation';
switch (true) {
case !!pos && !!pos.deviation:
if(!!pos && !!pos.deviation){
index = pos.index;
deviation = pos.deviation;
console.log(index);
console.log(deviation);
}
break;
case pos !== false:
console.log('pos');
break;
default:
break;
}