Narrowing
typeof
Truthiness
typeof null
> 'object'==, !=
自定义类型保护


Discriminated unions
never type
Last updated
function foo(str: string[] | null) {
if(typeof str === 'object'){
// 报错,因为 s 可能是 array,但也可能是 null!
for(const s of str){
...
}
}
}function foo(str: string[] | null) {
if(str && typeof str === 'object'){
// ok, 先进行了 truthiness 判断
for(const s of str){
...
}
}
}function foo(x: number | null | undefined) {
if (x != null) {
// x != null 实际上过滤掉了 null 和 undefined 两种情况
// 因此 x 一定是 number
console.log(x.toFixed(2))
}
}function isString(test: string | number): test is string {
return typeof test === 'string'
}
function foo(bar: any){
if(isString(bar)){
console.log("it's a string")
console.log(bar.toFixed(2)) // 会在编译时报错,因为 bar 是 string
}
}function isString(test: string | number): boolean {
return typeof test === 'string'
}
function foo(bar: any){
if(isString(bar)){
console.log("it's a string")
console.log(bar.toFixed(2)) // 编译时不会报错,而 runtime 时会报错
}
}interface Circle {
kind: "circle";
radius: number;
}
interface Square {
kind: "square";
sideLength: number;
}
function foo(shape: Circle| Square){
if(shape.kind === 'circle'){
// 这时候 shape 已经被 narrow 到 Circle
// 因此只能访问 radius 属性
console.log(shape.radius)
}
...
}function getArea(shape: Circle | Square) {
switch (shape.kind) {
case "circle":
return Math.PI * shape.radius ** 2;
case "square":
return shape.sideLength ** 2;
default:
// 这时候 shape 就是被 narrow 到 never
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}