平时开发中,有些场景总有种蹩手蹩脚的感觉,看到 Utility Types 才知道自己 native 了,很多场景 ts 都帮我们想好了。

Partial

设置 Type 某个类型为可选,并返回部分 Type 类型。

源码:

type Partial<T> = &#123; [P in keyof T]?: T[P]; &#125;;

interface Todo &#123;
  title: string;
  description: string;
&#125;

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) &#123;
  return &#123; ...todo, ...fieldsToUpdate &#125;;
&#125;

const todo1 = &#123;
  title: "organize desk",
  description: "clear clutter",
&#125;;

const todo2 = updateTodo(todo1, &#123;
  description: "throw out trash",
&#125;);

Required

Type 类型里面的某个类型为必要类型(必选项)。

源码

type Required<T> = &#123;
    [P in keyof T]-?: T[P];
&#125;;

-? 表示移除可选性?,这里移除指把可选项改为必选项,而不是移除可选项。

interface Props &#123;
  a?: number;
  b?: string;
&#125;

const obj: Props = &#123; a: 5 &#125;;
// 报错,确少 b 类型
const obj2: Required<Props> = &#123; a: 5 &#125;;

Readonly

只读属性,不可改写。

源码

type Readonly<T> = &#123; readonly [P in keyof T]: T[P]; &#125;;

interface Todo &#123;
  title: string;
&#125;

const todo: Readonly<Todo> = &#123;
  title: "Delete inactive users",
&#125;;
// 报错,不能被重新赋值
todo.title = "Hello";

Record<Keys,Type>

Kyes 的类型转化为 Type 的类型,类似于类型扩展。

源码

type Record<K extends keyof any, T> = &#123;
    [P in K]: T;
&#125;;

interface CatInfo &#123;
  age: number;
  breed: string;
&#125;

type CatName = "miffy" | "boris" | "mordred";

const cats: Record<CatName, CatInfo> = &#123;
  miffy: &#123; age: 10, breed: "Persian" &#125;,
  boris: &#123; age: 5, breed: "Maine Coon" &#125;,
  mordred: &#123; age: 16, breed: "British Shorthair" &#125;,
&#125;;
// const cats: Record<CatName, CatInfo>
cats.boris;

Pick<Type, Keys>

Type 的部分类型 Keys 挑出来,返回这部分类型。(拣选属性)

源码

type Pick<T, K extends keyof T> = &#123;
    [P in K]: T[P];
&#125;;

interface Todo &#123;
  title: string;
  description: string;
  completed: boolean;
&#125;


// type TodoPreview = &#123; title: string, completed: boolean &#125;
type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = &#123;
  title: "Clean room",
  completed: false,
&#125;;
// const todo: TodoPreview
todo;

Omit<Type, Keys>

移除 Type 类型中的 Keys 类型,返回新的类型。和 Pick 含义相对。

源码

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

interface Todo &#123;
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
&#125;

type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = &#123;
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
&#125;;

todo;
 
const todo: TodoPreview

type TodoInfo = Omit<Todo, "completed" | "createdAt">;

const todoInfo: TodoInfo = &#123;
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
&#125;;
// const todoInfo: TodoInfo
todoInfo;

Exclude<Type, ExcludedUnion>

Type 中排除可分配给 ExcludedUnion 的属性,剩余的属性构成新的类型

源码

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

// T0 = "b" | "c"
type T0 = Exclude<"a" | "b" | "c", "a">;

Extract<Type, Union>

Type 中抽出可分配给 Union 的属性构成新的类型(交集)。与Exclude相反。

源码

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

// T0 = "a"
type T0 = Extract<"a" | "b" | "c", "a" | "f">;

NonNullable

Type 类型中移除 nullundefined

源码

type NonNullable<T> = T extends null | undefined ? never : T;

// T0 = string | number

type T0 = NonNullable<string | number | undefined>;

Parameters

Type 是函数类型,返回函数的参数。

源码

type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;

declare function f1(arg: &#123; a: number, b: string &#125;): void

type T0 = Parameters<() => string>;  // []

type T1 = Parameters<(s: string) => void>;  // [string]

type T2 = Parameters<(<T>(arg: T) => T)>;  // [unknown]

type T4 = Parameters<typeof f1>;  // [&#123; a: number, b: string &#125;]

type T5 = Parameters<any>;  // unknown[]

type T6 = Parameters<never>;  // never

ReturnType

Type 是函数类型,返回 Type 的返回值

源码

type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

declare function f1(): &#123; a: number; b: string &#125;;
// T0 = string
type T0 = ReturnType<() => string>;
// T1 = void
type T1 = ReturnType<(s: string) => void>;
// T2 = unknown
type T2 = ReturnType<<T>() => T>;
// T3 = number[]
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
// T4 = &#123; a: number; b: string &#125;
type T4 = ReturnType<typeof f1>;

InstanceType

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

源码

type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;

class C &#123;
  x = 0;
  y = 0;
&#125;
// type T0 = C
type T0 = InstanceType<typeof C>;
// type T1 = any
type T1 = InstanceType<any>;
//  type T2 = never    
type T2 = InstanceType<never>;
// Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'. 
type T3 = InstanceType<string>;

ThisParameterType

返回函数的 this 参数类型,如果不是 this,返回 unknow 类型。

源码

type ThisParameterType<T> = T extends (this: infer U, ...args: any[]) => any ? U : unknown;

function toHex(this: Number) &#123;
  return this.toString(16);
&#125;
// n:number
function numberToString(n: ThisParameterType<typeof toHex>) &#123;
  return toHex.apply(n);
&#125;

function add(a: number, b: number) &#123;
  return a + b
&#125;
// unknown
type addParamerType = ThisParameterType<typeof add>

OmitThisParameter

如果一个函数有指定的 this 类型,那么返回一个不带 this 类型的函数类型,否则还是返回原来的函数。

源码

type OmitThisParameter<T> = unknown extends ThisParameterType<T> ? T : T extends (...args: infer A) => infer R ? (...args: A) => R : T;

function toHex(this: Number) &#123;
  return this.toString(16);
&#125;
// () => string
const fiveToHex: OmitThisParameter<typeof toHex> = toHex.bind(5);

ThisType

ThisType 不会返回一个转换之后的类型,提供基于上下文的 this 类型。注意,需要开启 --noImplicitThis 特性。

源码

interface ThisType<T> &#123; &#125;

type ObjectDescriptor<D, M> = &#123;
    data?: D;
    methods?: M & ThisType<D & M>;  // Type of 'this' in methods is D & M
&#125;

function makeObject<D, M>(desc: ObjectDescriptor<D, M>): D & M &#123;
    let data: object = desc.data || &#123;&#125;;
    let methods: object = desc.methods || &#123;&#125;;
    return &#123; ...data, ...methods &#125; as D & M;
&#125;

let obj = makeObject(&#123;
    data: &#123; x: 0, y: 0 &#125;,
    methods: &#123;
        moveBy(dx: number, dy: number) &#123;
            this.x += dx;  // Strongly typed this
            this.y += dy;  // Strongly typed this
        &#125;
    &#125;
&#125;);

obj.x = 10;
obj.y = 20;
obj.moveBy(5, 5);

参考