🤪🤪TS高级用法(二)

432 阅读2分钟

如今,越来越多的项目使用了TypeScript进行编写,我们都知道TypeScriptJavaScript的超集,它为JavaScript提供了强大的类型和语法增强功能,能在项目开发的过程中大大减少错误的产生。而TypeScript也内置了很多的工具类型,接下来,我将带着大家学习TypeScript中的工具类型。

本文中为系列文章的第二篇

Record

Record,翻译过来即是记录的意思,用于将一个类型中的属性值映射到另外一个类型。

栗子

interface PersonType {
  name: string;
  age?: number;
}
​
type Names = "_island" | "zhangsan" | "lisi";
​
// 将Names作为list的属性名称,PersonType作为属性值类型
// type Record<K extends string | number | symbol, T> = { [P in K]: T; }
const list: Record<Names, PersonType> = {
  _island: { age: 10, name: "_island" },
  zhangsan: { age: 5, name: "zhangsan" },
  lisi: { age: 16, name: "lisi" },
};

分析

我们可以看到,将KK只能是string number symbol类型)转化作为T类型。

type Record<K extends string | number | symbol, T> = { [P in K]: T; }

Omit

Omit用于忽略类型中的指定属性,创建一个新的类型。

栗子

interface CarType {
  name: string;
  type: string;
  color: string;
}
​
const C1: CarType = {
  name: "Car1",
  type: "mini",
  color: "red",
};
​
// 从CarType类型中,忽略color属性
// type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }
const C2: Omit<CarType, "color"> = {
  name: "Car1",
  type: "mini",
};

分析

T类型中去除K属性,通过keyof获取T类型中的属性,使用Exclude移除K属性。

type Omit<T, K extends string | number | symbol> = { [P in Exclude<keyof T, K>]: T[P]; }

Exclude

Exclude用于在将一个类型中属于另外一个类型的移除掉。

栗子

interface A {
  size: number;
  color: string;
}
​
interface B {
  size: number;
}
​
const C: Exclude<B, A> = {
  size: 100,
};

分析

如果T类型能分配给U,则返回never类型,否则返回T类型。

type Exclude<T, U> = T extends U ? never : T

Extract

栗子

interface AList {
    name:string;
    age:number;
    type:number
}
​
interface BList {
    name:string;
    age:number;
    type:number
    count:number
​
}
interface CList {
    name:string;
    age:number;
    type:number
​
}
​
// type Extract<T, U> = T extends U ? T : never
// type LT = BList
type LT= Extract<AList|BList|CList,BList>

分析

T类型中提取出U类型,如果T不能分配U,则never

type Extract<T, U> = T extends U ? T : never