typescript内置工具类型

68 阅读2分钟

参考文章:2022年了,我才开始学 typescript ,晚吗?(7.5k字总结) - 掘金 (juejin.cn)

  1. Required

将类型的属性变成必选

ts
 代码解读
复制代码
interface Person {
    name?: string,
    age?: number,
    hobby?: string[]
}

const user: Required<Person> = {
    name: "树哥",
    age: 18,
    hobby: ["code"]
}
  1. Partial

与 Required 相反,将所有属性转换为可选属性

ts
 代码解读
复制代码
interface Person {
    name: string,
    age: number,
}

const shuge:Person = {
  name:'树哥'
} // error  Property 'age' is missing in type '{ name: string; }' but required in type 'Person'.

从上面知道,如果必传而我们少穿传了的话,就会报错

我们使用 Partial 将其变为可选

ts
 代码解读
复制代码
type User = Partial<Person>

const shuge: User={
  name:'树哥'
} // 编译正确
  1. Exclude

Exclude<T, U> 的作用是将某个类型中属于另一个的类型移除掉,剩余的属性构成新的类型

ts
 代码解读
复制代码
type T0 = Exclude<"a" | "b" | "c", "a">; // "b" | "c"
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
type T2 = Exclude<string | number | (() => void), Function>; // string | number
  1. Extract

和 Exclude 相反,Extract<T,U> 从 T 中提取出 U。

ts
 代码解读
复制代码
type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T1 = Extract<string | number | (() => void), Function>; // () =>void

适用于:并集类型

  1. Readonly

把数组或对象的所有属性值转换为只读的,这就意味着这些属性不能被重新赋值。

ts
 代码解读
复制代码
interface Person {
  name: string;
  age: number;
  gender?: "male" | "female";
}

let p: Readonly<Person> = {
  name: "hello",
  age: 10,
  gender: "male",
};
p.age = 11; // error  Cannot assign to 'age' because it is a read-only property.
  1. Record

Record<K extends keyof any, T> 的作用是将 K 中所有的属性的值转化为 T 类型。

ts
 代码解读
复制代码
type Property = 'key1'|'key2'
type Person = Record<Property, string>;

const p: Person = {
  key1: "hello 啊",
  key2: "树哥",
};
  1. Pick

从某个类型中挑出一些属性出来

ts
 代码解读
复制代码
type Person = {
  name: string;
  age:number;
  gender:string
}

type P1 = Pick<Person, "name" | "age">; // { name: string; age: number; }

const user:P1={
  name:'树哥',
  age:18
}
  1. Omit

与Pick相反,Omit<T,K> 从T中取出除去K的其他所有属性。

ts
 代码解读
复制代码
interface Person {
  name: string,
  age: number,
  gender: string
}
type P1 = Omit<Person, "age" | "gender">
const user:P1  = {
  name: '树哥'
}
  1. NonNullable

去除类型中的 nullundefined

ts
 代码解读
复制代码
type P1 = NonNullable<string | number | undefined>; // string | number
type P2 = NonNullable<string[] | null | undefined>; // string[]
  1. ReturnType

用来得到一个函数的返回值类型

ts
 代码解读
复制代码
type Func = (value: string) => string;
const test: ReturnType<Func> = "1";
  1. Parameters

用于获得函数的参数类型所组成的元组类型。

ts
 代码解读
复制代码
type P1 = Parameters<(a: number, b: string) => void>; // [number, string]
  1. InstanceType

返回构造函数类型T的实例类型

ts
 代码解读
复制代码
class C {
  x = 0;
  y = 0;
}

type D = InstanceType<typeof C>;  // C

作者:呛再首
链接:juejin.cn/post/712411…
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。