typescript进阶
一、环境准备
参考基础《TODO》
二、联合类型和类型保护
interface Bird {
fly: boolean;
sing: () => {};
}
interface Dog {
fly: boolean;
bark: () => {};
}
// 联合类型
function trainAnimal(animal: Bird | Dog) {
if (animal.fly) {
// 1、类型断言
(animal as Bird).sing();
}
}
function trainAnimal2(animal: Bird | Dog) {
// 2、in || typeof || instanceof
if ("sing" in animal) {
animal.sing;
}
}
三、泛型
函数的括号前面定义
可以显示的指定也可利用类型推断自动推断。
// 实现字符串类型的拼接
function jion<ABC>(first: ABC, second: ABC) {
return `S{first}${second}`;
}
jion<number>(1, 1);
class DataManager<T> {
constructor(private data: T[]) {}
getItem(index: number): T {
return this.data[index];
}
}
// 匿名函数
const test = function (a: any, b: any) {
return a * b;
};

浙公网安备 33010602011771号