category
Technology
Tags
TypeScript
Utility Types
Collection
CreateTime
Aug 29, 2022 02:45 AM
UpdateTime
Dec 11, 2023 12:09 PM
Published
Published
Partial<T>Required<T>Readonly<T>Record<K, T>Pick<T, K>Omit<T, K>Exclude<T, U>Extract<T, U>NonNullable<T>Parameters<T>ConstructorParameters<T>ReturnType<T>InstanceType<T>ThisParameterType<T>OmitThisParameter<T>ThisType<T>
Partial<T>
将T的所有类型转换为可选类型,返回的类型可以为T的所有子集
interface Todo { title: string; description: string; } type subTodo = Partial<Todo> const todo1: subTodo = { title: 'This is a title' } const todo2: subTodo = { description: 'This is a description' }
Required<T>
与Partial相反,将T的所有类型设为必选
interface Todo { title?: string; description?: string; } const todo1: Todo = { title: 'This is a title' } const todo2: Todo = { description: 'This is a description' } const todo3: Required<Todo> = { // 'description' is declared here. title: '123' }
Readonly<T>
将T的所有类型设为只读
interface Todo { title: string; } const todo: Readonly<Todo> = { title: 'This is a title' } todo.title = 'new title' // Cannot assign to 'title' because it is a read-only property.
Record<K, T>
将一组属性K的类型设为T
interface Todo { title: string; } type TodoList = 'todo1' | 'todo2' const todos: Record<TodoList, Todo> = { todo1: { title: 'todo1' }, todo2: { title: 'todo2' } }
Pick<T, K>
从T中选出一组K构建出新类型
interface Todo { title: string; description: string; done: boolean; } type TodoPreview = Pick<Todo, 'title' | 'done'> const todo: TodoPreview = { title: 'title', done: true }
Omit<T, K>
从T中删除属性K,与Pick相反
interface Todo { title: string; description: string; done: boolean; } type TodoPreview = Omit<Todo, 'description' | 'done'> const todo: TodoPreview = { title: 'title' }
Exclude<T, U>
从联合T中排除U
type Todo = string | number | (() => void) type TodoPreview = Exclude<Todo, string> // type TodoPreview = number | (() => void)
Extract<T, U>
与Exclude相反,从T中提取U相同的属性构建新的类型
type Todo = string | number | (() => void) type TodoPreview = Extract<Todo, string> // type TodoPreview = string
NonNullable<T>
从T中剔除null和undefined类型
type Todo = NonNullable<number | string | null | undefined> // tyoe Todo = <number | string>
Parameters<T>
从类型为T的函数的参数返回元祖类型Type
type T0 = Parameters<() => string> // type T0 = [] type T1 = Parameters<(s: string) => void> // type T1 = [s: string]
ConstructorParameters<T>
从构造函数类型的类型构造元组或数组类型。它产生一个包含所有参数类型的元组类型(或者
never如果Type不是函数的类型)。type T0 = ConstructorParameters<ErrorConstructor>; // type T0 = [message?: string] type T1 = ConstructorParameters<FunctionConstructor>; // type T1 = string[] type T2 = ConstructorParameters<RegExpConstructor>; // type T2 = [pattern: string | RegExp, flags?: string] type T3 = ConstructorParameters<any>; // type T3 = unknown[]
ReturnType<T>
构造一个由 function 的返回类型组成的类型
Type。type T0 = ReturnType<() => string> // type T0 = string
InstanceType<T>
返回构造函数类型T的实例类型
class C { x = 0; y = 0; } type T0 = InstanceType<typeof C>; // C type T1 = InstanceType<any>; // any type T2 = InstanceType<never>; // any