ts

使用ts内置工具泛型

使用ts内置工具泛型

Posted by nolan on November 9, 2021

Record

type Record<K extends keyof any, T> = {
  [P in K]: T;
};

可用来声明对象结构的类型。

type Foo = Record<'a' | ‘b’, string>

const foo: Foo = {a: '1'} // 正确
const foo: Foo = {b: '1'} // 错误,因为 key 不为 a
const foo: Foo = {a: 1} // 错误,因为 value 的值不是 string 类型

Partial

type Partial<T> = {
  [P in keyof T]?: T[P];
};

将传入的接口的必选属性变为可选属性。

interface iPeople {
    title: string;
    name: string;
}


const people: Partial<iPeople> = {
    title: 'Delete inactive users',
};

Required

type Required<T> = {
  [P in keyof T]-?: T[P];
};

将传入的接口的可选属性变为必选属性

interface iPeople {
title?: string;
name?: string;
}


const people: Required<iPeople> = { title: 'ts' }; // Error: property 'name' missing

Readonly

type Readonly<T> = {
  readonly [P in keyof T]: T[P];
};

将传入的接口的属性变为只读属性

interface iPeople {
    title: string;
    name: string;
}

const people: Readonly<iPeople> = {
    title: 'todo list';
    name: 'ts';
};
// title name属性就是只读的了

Pick

<T, K extends keyof T> = {
  [P in K]: T[P];
};

从传入的接口的中提取一部分属性作为新的接口。

interface iPeople {
name: string;
age: number;
gender: number;
}

const pickPerson: Pick<iPeople, 'name' | 'age'> = {name: 'test', age: 22};

Exclude

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

排除掉T中可以赋值给U的类型。

type ExcludeType = Exclude<"a" | "b" | "c" | "d", "a" | "c" | "f">;
// ExcludeType = 'b' | 'd'

Extract

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

提取出 T 中可以赋值给 U 的类型。

type ExtractType = Extract<"a" | "b" | "c" | "d", "a" | "c" | "f">;
// ExcludeType = 'a' | 'c'

Omit

type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

基于 T 生成新的 type,其中排除掉了在 K 中的属性。

interface iPeople {
name: string;
age: number;
gender: number;
}
type OmitPeople = Omit<iPeople, 'name'>;
// OmitPeople = { age: number, gender: number}

NonNullable

NonNullable<T>

从 T 中剔除 null 和 undefined

例子

type NonNullableType = string | number | null | undefined;

function showType(args: NonNullable<NonNullableType>) {
    console.log(args);
}

showType(1);
// Output: 1

showType(null);
// Error: Argument of type 'null' is not assignable to parameter of type 'string | number'.