『TypeScript』实用类型
coderfee/Aug 28, 2019/#TypeScript#
Partial<T>
它会构造一个新类型,并将类型 T
的所有属性设置为可选。该类型是类型 T
的子集。
interface User {name: stringage: number}const a: User = {name: 'tom',// age: 16}// Errorconst b: Partial<User> = {name: 'simon',}// OK
如果用 TypeScript 手动实现,代码如下:
type Partial<T> = {[P in keyof T]?: T[P]}
Readonly<T>
它将构造一个新类型,并将类型 T
的所有属性设置为 readonly
,这意味着新类型的属性都不能重新赋值了。
interface User {name: stringage: number}let tom: Readonly<User> = {name: 'tom',age: 16,}tom.name = 'simon' // Error
TypeScript 手动实现如下:
interface User {name: stringage: number}type Readonly<T> = {readonly [P in keyof T]: T[P]}
Record<K, T>
构造一个具有类型 T
的一组属性 K
的新类型,该类型经常用于将一种类型的属性映射到另一种类型上。
interface Page {title: string}type PageInfo = 'home' | 'about' | 'contact'const x: Record<PageInfo, Page> = {home: { title: 'home' },about: { title: 'about' },contact: { title: 'contact' },}
Pick<T, K>
从类型 T
中选取一些属性 K
作为新类型。
interface Todo {title: stringdescription: stringcompleted: boolean}type TodoPreview = Pick<Todo, 'title' | 'completed'>const todo: TodoPreview = {title: 'Todo',completed: true,}
Omit<T, K>
从类型 T
中选取所有属性,然后再移除指定的 K
类型的属性。
interface Todo {title: stringdescription: stringcompleted: boolean}type TodoPreview = Omit<Todo, 'description'>const todo: TodoPreview = {title: 'Todo',completed: true,}
Exclude<T, U>
通过从类型 T
中排除可分配给类型 U
来构造新类型。
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'> // 'c'type T2 = Exclude<string | number | (() => void), Function> // string | number
Extract<T, U>
通过提取类型 T
中可以分配给类型 U
来构造新类型。
type T1 = Extract<'a' | 'b', 'c', 'a' | 'b'> // 'a' | 'b'type T2 = Extract<string | number | (() => void), Function> // Function
NonNullable<T>
从类型 T
中排除 null
和 undefined
。
type T1 = NonNullable<string | number | null> // string | numbertype T2 = NonNullable<string[] | null | undefined> // string[]
Required<T>
构造一个新类型,并将类型 T
的所有属性设置为必选。
interface User {name?: stringage?: number}const tom: User = {name: 'tom',}// OKconst simon: Required<User> = {name: 'simon',// age: 16,}// Error
ThisType<T>
它不返回任何转换类型,仅作为 this
上下文的标记。要使用该类型,必须在 tsconfig.json
中启用 noImplicitThis
。