/*
缩小就是对联合类型的详细判断
使用类型缩小使代码变得更加简洁准确安全
*/
function padLeft(padding: number | string, input: string) {
if (typeof padding === "number")
return new Array(padding + 1).join(" ") + input;
return padding + input;
}
function printAll(strs: string | string[] | null) {
if (strs && typeof strs === "object") {
// null 也为 object
for (const s of strs) {
console.log(s);
}
} else if (typeof strs === "string") {
console.log(strs);
}
}
printAll(null);
console.log(typeof null); //object
function check(num: number | string) {
if (num) {
// if(0) == false
console.log(num);
}
}
//if(' ') == ' ' if('') == false
check("12");
function multiplyAll(
valuses: number[] | undefined,
factor: number
): number[] | undefined {
if (!valuses) {
return valuses;
} else {
return valuses.map((x) => x * factor);
}
}
const arr = [1, 2, 3, 4, 5];
console.log(typeof arr); // object
// 类型谓词
type Fish = { name: "fish"; swim: () => void };
type Bird = { name: "bird"; fly: () => void };
let fish: Fish = {
name: "fish",
swim() {
console.log("i can swim");
},
};
let bird: Bird = {
name: "bird",
fly() {
console.log("I can fly");
},
};
function getSmallPet(): Fish | Bird {
if (Math.random() < 0.5) {
return fish;
} else {
return bird;
}
}
function isFish(pet: Fish | Bird): pet is Fish {
return (pet as Fish).swim !== undefined;
// as 类型断言 将 pet转化为 Fish
}
let p = getSmallPet();
if (isFish(p)) {
p.swim();
} else {
p.fly();
}
const zoo: (Fish | Bird)[] = [
getSmallPet(),
getSmallPet(),
getSmallPet(),
getSmallPet(),
];
const underWater1: Fish[] = zoo.filter(isFish);
// []
const underWater2: Fish[] = zoo.filter(isFish) as Fish[];
// []
console.log("underWater1", underWater1);
console.log(underWater2);
console.log(Math.PI);
type Circle = {
kind: "Circle";
radius: number;
};
interface Square {
kind: "square";
sideLength: number;
}
type Shape = Circle | Square;
function getArea(shape: Shape) {
if (shape.kind == "Circle") {
return Math.PI * shape.radius ** 2;
} else {
return shape.sideLength ** 2;
}
}
console.log(
getArea({
kind: "Circle",
radius: 2,
})
);
console.log(
getArea({
kind: "square",
sideLength: 5,
})
);
export {}
typescript Narrowing
最新推荐文章于 2024-11-04 16:17:23 发布