什么是类型缩小?
- 类型缩小的英文是Type Narrowing ;
- 我们可以通过类似于typeof padding === "number”的判断语句,来改变TypeScript的执行路径;
- 在给定的执行路径中,我们可以缩小比声明时更小的类型,这个过程称之为缩小;
- 而我们编写的 typeof padding === "number可以称之为类型保护( type guards ) ;
- 常见的类型缩小主要有如下几种:
- typeof
- 平等缩小(比如===、!== )
- instanceof
- in
1、typeof
type IDType = number | string;
function prientID(id: IDType) {
if (typeof id === "string") {
console.log(id.toLocaleUpperCase);
} else {
console.log(id);
}
}
2、平等缩小(比如===、!== )
type Direction = "left" | "right" | "center";
function prientDirection(direction: Direction) {
if (direction === "left") {
console.log(direction);
}
switch (direction) {
case "left":
console.log(direction);
break;
case 'center':
console.log(direction)
...
}
}
3、instanceof
function prientTime(time:string | Date){
if(time instanceof Date){
console.log(time.toUTCString)
}else{
console.log(time)
}
}
4、in
type Fish = { swinming: () => void };
type Dog = { running: () => void };
function walk(animal: Fish | Dog) {
if('swinming' in animal){
animal.swinming
}else{
animal.running
}
}
const fish: Fish = {
swinming() {
console.log("swinming");
},
};