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;
};
posted @   一颗米  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示