【TypeScript】基础知识

TypeScript 基础知识

ts 网站推荐

  • 在线 code 网站
    https://www.typescriptlang.org/play/
    https://playcode.io/
    https://codesandbox.io/
  • 类型体操
    https://github.com/type-challenges/type-challenges
  • 学习教程
    https://www.typescriptlang.org/docs/

ts 比 js 多的类型

void、never、enum、unknown、any,再加上自定义类型type、interface

enum 使用建议

推荐用来映射 number 类型,不推荐用来映射 string 类型(可以用 type 来映射)


// 推荐
enum Permission { 
  Read = 0,
  Write = 1 << 1,
  Execute = 1 << 2,
  Delete = 1 << 3,
}

// 不推荐
enum Fruit {
  Apple = 'apple',
  Banana = 'banana',
  Orange = 'orange',
  Pomegranate = 'pomegranate',
}

// 上面场景更建议用 type 来定义
type Fruit = 'apple' | 'banana' | 'orange' | 'pomegranate'

type 和 interface 的区别

type类型别名(type alias),用于给各种类型定义别名(注意不是类型声明)
interface是接口,用于描述对象的属性(包括函数、非函数)

区别1:

  • interface 只描述对象
  • type 描述所有数据

区别2:

  • type 只是别名
  • interface 是类型声明

区别3:

  • type 不可重新赋值,所以对内 API 尽量用 type,防止代码分散
  • interface 可以自动合并重复的声明,所以对外 API 尽量用 interface,方便扩展

区别4:

  • 遇到属性冲突的时候(比如交叉类型),interface 会在定义类型的时候就报错,而 type 只会变成 never

ts 中联合类型如何收窄

  1. 【js 方法】typeof 、instanceof、in

    type ID = string | number | { id: number } | Array<number>
    function getId(id: ID) {
      if (typeof id === 'string') {
        console.log(id.length);
      } else if (typeof id === 'number') {
        console.log(id.toFixed(2));
      } else if (id instanceof Array) {
        console.log(id.join('-'));
      } else if ('id' in id) {
        console.log(id.id);
      }
    }
    
  2. 【ts 方法】用 is 关键字

    缺点:写起来有点麻烦

    type Fish = { swim: () => void }
    type Bird = { fly: () => void }
    type Pet = Fish | Bird 
    
    function move(pet: Pet) {
      if (isFish(pet)) {
        pet.swim();
      } else {
        pet.fly();
      }
    }
    
    // 类型判断一定要用 function 这种写法
    function isFish(pet: Pet): pet is Fish {
    
      // 这里就可以用 js 中的 in、instanceof、type 各种方法来进行判断
    
      // 方法一
      // return (pet as Fish).swim !== undefined
    
      // 方法二
      return 'swim' in pet
    
    }
    
  3. 【ts 方法】可辨别联合类型
    要求 T = A | B | C | D

    • A、B、C、D… 有相同属性 kind 或其他
    • kind 的类型是简单类型
    • 各类型中的 kind 无交集

    则称 T 为可辨别联合

    一句话总结:同名、可辨别的简单类型的 key

    type Fish = { kind: 'fish', swim: () => void }
    type Bird = { kind: 'bird', fly: () => void }
    type Pet = Fish | Bird
    
    function move(pet: Pet) {
      if (pet.kind === 'fish') {
        pet.swim();
      } else {
        pet.fly();
      }
    }
    
  4. 【ts 方法】断言

    type Fish = { kind: 'fish', swim: () => void }
    type Bird = { kind: 'bird', fly: () => void }
    type Pet = Fish | Bird
    
    function move(pet: Pet) {
      const fish = pet as Fish
      fish.swim()
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值