xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

TypeScript Utility Types All In One

TypeScript Utility Types All In One

TypeScript v4.8.4

Awaited<Type>
Partial<Type>
Required<Type>
Readonly<Type>
Record<Keys, Type>
Pick<Type, Keys>
Omit<Type, Keys>
Exclude<UnionType, ExcludedMembers>
Extract<Type, Union>
NonNullable<Type>
Parameters<Type>
ConstructorParameters<Type>
ReturnType<Type>
InstanceType<Type>
ThisParameterType<Type>
OmitThisParameter<Type>
ThisType<Type>
// Intrinsic String Manipulation Types
Uppercase<StringType>
Lowercase<StringType>
Capitalize<StringType>
Uncapitalize<StringType>

https://www.typescriptlang.org/docs/handbook/utility-types.html

Awaited<Type>

This type is meant to model operations like await in async functions, or the .then() method on Promises - specifically, the way that they recursively unwrap Promises.

这种类型旨在模拟异步函数中的 awaitPromises 上的 .then() 方法等操作 - 特别是它们递归解包 Promises 的方式。

type A = Awaited<Promise<string>>;
// type A = string

type B = Awaited<Promise<Promise<number>>>;
// type B = number

type C = Awaited<boolean | Promise<number>>;
// type C = number | boolean

Partial<Type>

Constructs a type with all properties of Type set to optional. This utility will return a type that represents all subsets of a given type.

构造一个类型,其中 Type 的所有属性都设置为可选。此实用程序将返回一个表示给定类型的所有子集的类型。

interface Todo {
  title: string;
  description: string;
}

// type Test = Partial<number>;
// type Partial<T> = { [P in keyof T]?: T[P] | undefined; }

// 把一个类型的`所有属性`都变成`可选的`, 生成一个新类型 ✅
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  // (parameter) todo: Todo
  // (parameter) fieldsToUpdate: Partial<Todo>
  return {
    ...todo,
    ...fieldsToUpdate,
  };
}
/* 
function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>): {
    title: string;
    description: string;
}
*/

const todo1 = {
  title: "organize desk",
  description: "clear clutter",
};
/* 
const todo1: {
    title: string;
    description: string;
}
*/

const todo2 = {
  description: "throw out trash",
};
/*
const todo2: {
    description: string;
}
*/

const todo = updateTodo(todo1, todo2);
/*
const todo: {
    title: string;
    description: string;
}
*/


Required<Type>

Constructs a type consisting of all properties of Type set to required. The opposite of Partial.

构造一个类型,该类型由设置为 required 的 Type 的所有属性组成。与 Partial 正好相反。


interface Props {
  a: number;
  b?: string;
  c?: string;
}

const obj1: Props = { a: 5 };
const obj2: Props = { a: 5, c: 'c' };

// 把一个类型的`所有属性`都变成`required`, 生成一个新类型 ✅
const obj3: Required<Props> = { a: 5, b: 'b', c: 'c' };
// type Required<T> = { [P in keyof T]-?: T[P]; }
// const obj3: Required<Props>

const obj4: Required<Props> = { a: 5 };
// ❌ Type '{ a: number; }' is missing the following properties from type 'Required<Props>': b, c(2739)

Readonly<Type>

Constructs a type with all properties of Type set to readonly, meaning the properties of the constructed type cannot be reassigned.

构造一个 Type 的所有属性都设置为 readonly 的类型,这意味着构造类型的属性不能被重新分配。


// @errors: 2540
interface Todo {
  title: string;
}

// 把一个类型的`所有属性`都变成 `readonly`, 生成一个新类型 ✅
const todo: Readonly<Todo> = {
  title: "Delete inactive users",
};

// readonly 不可重新赋值
todo.title = "Hello";
// const todo: Readonly<Todo>
// ❌ (property) title: any
// Cannot assign to 'title' because it is a read-only property.(2540)

This utility is useful for representing assignment expressions that will fail at runtime (i.e. when attempting to reassign properties of a frozen object).

此实用程序对于表示将在运行时失败(例如,尝试重新分配冻结对象的属性时)的赋值表达式很有用。

Object.freeze

function freeze<Type>(obj: Type): Readonly<Type>;
// function freeze<Type>(obj: Type): Readonly<Type>
// ❌ Function implementation is missing or not immediately following the declaration.(2391)


Record<Keys, Type>

Constructs an object type whose property keys are Keys and whose property values are Type. This utility can be used to map the properties of a type to another type.

构造一个对象类型,其属性键为 Keys,其属性值为 Type。此实用程序可用于将一种类型的属性映射到另一种类型。

interface CatInfo {
  age: number;
  breed: string;
}

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

// 把`一种类型`的`字段/属性` 映射到 `另一种类型`的`字段/属性`上,起到类型`字段/属性`复用的功能
const cats: Record<CatName, CatInfo> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
  mordred: { age: 16, breed: "British Shorthair" },
};

cats.boris;
// const cats: Record<CatName, CatInfo>
// (property) boris: CatInfo

cats.mordred;
// const cats: Record<CatName, CatInfo>
// (property) mordred: CatInfo

https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkeys-type

Pick<Type, Keys>

Constructs a type by picking the set of properties Keys (string literal or union of string literals) from Type.

通过从 Type 中选择/挑选一组属性 Keys(字符串文字或字符串文字的联合)来构造一个类型。

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

// 从一个类型中`挑选出`一些`字段/属性`,生成一个有该类型的`字段/属性`子集组成的一个新类型 ✅
type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

todo;
// const todo: TodoPreview

https://www.typescriptlang.org/docs/handbook/utility-types.html#picktype-keys

Omit<Type, Keys>

Constructs a type by picking all properties from Type and then removing Keys (string literal or union of string literals).

通过从 Type 中选择所有属性然后删除 Keys(字符串文字或字符串文字的联合)来构造一个类型。

interface Todo {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}

// `过滤掉`一些`字段/属性`构成一个新的`字段/属性`子集 ✅
type TodoPreview = Omit<Todo, "description">;
/*
// 等价于
type TodoPreview = {
    title: string;
    completed: boolean;
    createdAt: number;
}
*/

const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
  createdAt: 1615544252770,
};

todo;
// const todo: TodoPreview


// `过滤掉`一些`字段/属性`构成一个新的`字段/属性`子集
type TodoInfo = Omit<Todo, "completed" | "createdAt">;
/*
// 等价于
type TodoInfo = {
    description: string;
    title: string;
}
*/

const todoInfo: TodoInfo = {
  title: "Pick up kids",
  description: "Kindergarten closes at 5pm",
};

todoInfo;
// const todoInfo: TodoInfo

https://www.typescriptlang.org/docs/handbook/utility-types.html#omittype-keys

Exclude<UnionType, ExcludedMembers>

Constructs a type by excluding from UnionType all union members that are assignable to ExcludedMembers.

通过从 联合类型排除所有可分配给 ExcludedMembers 的联合成员来构造类型。

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

type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
// type T1 = "c"
type T2 = Exclude<string | number | (() => void), Function>;
// type T2 = string | number

type Shape =
  | { kind: "circle"; radius: number }
  | { kind: "square"; x: number }
  | { kind: "triangle"; x: number; y: number };

type T3 = Exclude<Shape, { kind: "circle" }>
// type T3 = { kind: "square"; x: number; } | { kind: "triangle"; x: number; y: number; }

https://www.typescriptlang.org/docs/handbook/utility-types.html#excludeuniontype-excludedmembers

Extract<Type, Union>

// 

NonNullable<Type>

// 

Parameters<Type>

// 

ConstructorParameters<Type>

// 

ReturnType<Type>

Constructs a type consisting of the return type of function Type.

构造一个由函数 Type返回类型组成的类型。

// ReturnType 实现原理,范型,推断 ❓
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any
declare function f1(): { a: number; b: string };
type T4 = ReturnType<typeof f1>;
/*
type T4 = {
    a: number;
    b: string;
}
*/

type T0 = ReturnType<() => string>;
// type T0 = string

type T1 = ReturnType<(s: string) => void>;
// type T1 = void

type T2 = ReturnType<<T>() => T>;
// type T2 = unknown

type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
// type T3 = number[]

type T5 = ReturnType<any>;
// type T5 = any

type T6 = ReturnType<never>;
// type T6 = never

type T7 = ReturnType<string>;
// Type 'string' does not satisfy the constraint '(...args: any) => any'.
// type T7 = any

type T8 = ReturnType<Function>;
// 'Function' does not satisfy the constraint '(...args: any) => any'.
// Type 'Function' provides no match for the signature '(...args: any): any'.
// type T8 = any

获取函数类型返回类型

/**
 * Obtain the return type of a function type
 * 获取函数类型的返回类型
 */
// type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

// the predefined type ReturnType<T>
// 预定义类型 ReturnType<T> ✅
type Predicate = (x: unknown) => boolean;

type RT = ReturnType<Predicate>;
// type RT = boolean


function func() {
  return { x: 10, y: 3, };
}

// typeof
type FRT = ReturnType<typeof func>;
/*
type FRT = {
  x: number;
  y: number;
}
*/

type FRT_err = ReturnType<func>;
// 'func' refers to a value, but is being used as a type here.Did you mean 'typeof func' ? ts(2749)



https://www.typescriptlang.org/docs/handbook/utility-types.html#returntypetype

InstanceType<Type>

// 

ThisParameterType<Type>

// 

OmitThisParameter<Type>

// 

ThisType<Type>

// 

Intrinsic String Manipulation Types

Uppercase<StringType>

// 

Lowercase<StringType>

// 

Capitalize<StringType>

// 

Uncapitalize<StringType>

// 

refs

TypeScript Advanced Types All In One

https://www.cnblogs.com/xgqfrms/p/15877490.html

https://github.com/xgqfrms/learn-typescript-by-practice/issues/21

https://github.com/xgqfrms/learn-typescript-by-practice/issues/22

https://github.com/xgqfrms/learn-typescript-by-practice/issues/23



©xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!


posted @ 2022-10-15 20:29  xgqfrms  阅读(35)  评论(7编辑  收藏  举报