适用场景
变量的类型可能为空值(null或undefined),但是在某些确定场景中变量不为空值。但是ts会编译报错。这个时候,可以用非空断言符号!将变量的值限定为其类型的非空值。
举个例子
假设有个学生的类型如下。
interface StudentInfo {
id: number;
score?: { math: number }
}
用addDefaultScore方法给学生信息加兜底逻辑。
const addDefaultScore = (s: StudentInfo) => {
if (!s.score) {
s.score = { math: 0 };
}
return s;
};
用getMathScore方法获取学生的数学成绩。
const getMathScore = (s: StudentInfo) => {
s = addDefaultScore(s);
return s.score.math;
};
getMathScore({ id: 1 });
会有如下报错:
由上面的代码看到,我们已经给学生添加了兜底成绩s.score = { math: 0 },s.score一定不为空。 这个时候可以用!将s.score限定为非空类型,即s.score!
const getMathScore = (s: StudentInfo) => {
s = addDefaultScore(s);
return s.score!.math;
};
这样就解决了上面的ts类型报错问题。
总结
变量后加非空断言符号!可以将null和undefined从变量的取值中排除,将变量限定为非空类型。