美文网首页
你不知道的TypeScript工具类型

你不知道的TypeScript工具类型

作者: 醉生夢死 | 来源:发表于2024-04-01 19:29 被阅读0次

现代化前端开发中, TypeScript已然成为重要的必备技能. 由于TypeScript知识比较多, 本文只介绍以下几点

  • typeinterface 的区别
  • any, unkonwn, never
  • 常用的工具类Partial, Required, Readonly, Pick, Omit, Extract, Exclude

话不多说, 直接进入主题

想练习的话,推荐使用 在线TypeScript Playground

type 和 interface 的区别

interface可以重复声明, 可以继承. type 则不行.

在对象扩展的情况下, 使用接口继承要比交叉类型的性能更好. 建议使用 interface 来描述对象对外暴露的接口.

使用 type 将一组类型重命名, 或对类型进行复杂编程, type 适合用于枚举值.

interface IMan {
    name: string;
    age?: number;
}

// 接口可以进行声明合并
interface IMan {
    hobby: string;
}

type TMan = {
    name: string;
    age?: number;
    country: string;
}

// type 不能重复定义
// type TMan = {}

// 接口可继承接口, 使用 extends 关键字
interface IManPlus extends IMan {
    weight: string;
}

// 接口可继承 type, 使用 extends 关键字
interface IManStudent extends TMan {
    gender: 'male' | 'female'
}

// 接口可多继承
interface IManTeacher extends IMan, TMan {}


// type可使用联合类型 & 类似于继承效果
type TManPlus1 =  TMan & { height: string }
type TManPlus2 =  { height: string } & TMan


let a: IManStudent = {
    gender: 'female',
    name: '张哈',
    country: '中国'
}

let b: IManTeacher = {
    name: '张哈',
    country: '中国',
    hobby: '篮球'
}

let c: TManPlus1 = {
    name: '戴维',
    country: '美国',
    height: '170cm',
}

any、unkonwn、never

anyunkonwn在TS类型中属于最顶层的Top Type,即所有的类型都是它俩的子类型。而never则相反,它作为Bottom Type是所有类型的子类型。

常用的工具类

  • Partial: 部分属性(可无)
  • Required: 所有属性都需要
  • Readonly: 所有属性只读
  • Pick: 选取部分属性
  • Omit: 剔除部分属性
  • Extract: 取交集
  • Exclude: 取差集
// Partial
const iMainPartial: Partial<IMan> = { // 可无
}

const tMainPartial: Partial<TMan> = {
    name: '取Type部分属性'
}


// Required
const iMainRequired: Required<IMan> = {
    name: '所有属性都得有',
    age: 20,
    hobby: '没有会报错'
}

const tMainRequired: Required<TMan> = {
    name: '所有属性都得有',
    age: 20,
    country: '中国'
}

// Readonly
const iMainReadonly: Readonly<IMan> = {
    name: '李四',
    // age: 12,
    hobby: '游泳'
}

// 无法为 iMainReadonly 任意属性赋值, 因为它所有属性都是只读
// iMainReadonly.age = 20










interface Car {
    brand: string;
    price: number;
    isSale: boolean;
    publishTime?: string
}

// Pick
type PickedCar = Pick<Car, 'brand' | 'isSale' | 'publishTime'> // 从 Car 中挑选属性

// Omit
type OmitCar = Omit<Car, 'isSale'> // 从 Car 中排除哪些属性



type SetA = 1 | 2 | 3 | 4
type SetB = 4 | 5 | 6

// Extract
type AExtractB = Extract<SetA, SetB> // 取交集 4


// Exclude
type AExcludeB = Exclude<SetA, SetB> // 从 A 里面剔除和 B 有交集的 4, 最后变成 1 | 2 | 3
type BExcludeA = Exclude<SetB, SetA> // 从 B 里面剔除和 C 有交集的 5, 最后变成 5 | 6

相关文章

网友评论

      本文标题:你不知道的TypeScript工具类型

      本文链接:https://www.haomeiwen.com/subject/bruitjtx.html