工具类型 - TypeScript 类的类型
工具类型
Typescript 提供了一些工具,来辅助进行常见的类型转换。这些类型全局可用。
Awaited
此类型用于对async
异步函数中的await
上,或应用于Promise递归展开.then()
方法上。
type A = Awaited; // type A = string type B = Awaited; // type B = number type C = Awaited; // type C = number | boolean
Partial
用于构造一个类型,类型的所有属性都设置为可选。这个工具返回代表给定类型的所有子集的类型。
interface Todo { title: string; description: string; } function updateTodo(todo: Todo, fieldsToUpdate: Partial) { return { ...todo, ...fieldsToUpdate }; } const todo1 = { title: "organize desk", description: "clear clutter", }; const todo2 = updateTodo(todo1, { description: "throw out trash", // description?: string | underfined }); /* const todo2: { title: string; description: string; } */
Required
用于构造一个类型,类型的所有属性都设置为必填的类型。这个工具类型跟Partial
相反。
interface Props { a?: number; b?: string; } const obj: Props = { a: 5 }; const obj2: Required = { a: 5 }; // TypeError: Property 'b' is missing in type '{ a: number; }' but required in type 'Required'.
Readonly
用于构造一个类型,类型的所有属性都设置为readonly
的类型。意味着这个类型的所有的属性全都不可以重新赋值。
interface Todo { title: string; } const todo: Readonly = { title: "Delete inactive users", }; todo.title = "Hello"; // TypeError: Cannot assign to 'title' because it is a read-only property.
这个工具类型用于表示在运行时失败的赋值表达式(即尝试重新分配冻结对象的属性时)。
Object.freeze
function freeze(obj: Type): Readonly;
Record
用于构造一个对象类型,它所有的键都是Keys
类型,它所有的值都是Type
类型。这个工具类型可以被用于映射一个类型的属性到另一个类型。
interface CatInfo { age: number; breed: string; } type CatName = "miffy" | "boris" | "mordred"; const cats: Record = { miffy: { age: 10, breed: "Persian" }, // (property) miffy: CatInfo boris: { age: 5, breed: "Maine Coon" }, // (property) boris: CatInfo mordred: { age: 16, breed: "British Shorthair" }, // (property) mordred: CatInfo }; // const cats: Record
Pick
用于构造一个类型,它是从Type
类型里面,挑选出属性Keys
(Keys是字符串字面量或者字符串字面量的联合类型)
interface Todo { title: string; description: string; completed: boolean; } type TodoPreview = Pick; /* type TodoPreview = { title: string; completed: boolean; } */ const todo: TodoPreview = { title: "Clean room", completed: false, }; todo; // const todo: TodoPreview
Omit
用于构造一个类型,它是从Type
类型里面,过滤掉属性Keys
(Keys 是字符串字面量或者字符串字面量的联合类型)
interface Todo { title: string; description: string; completed: boolean; createdAt: number; } type TodoPreview = Omit; /* 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; /* type TodoInfo = { title: string; description: string; } */ const todoInfo: TodoInfo = { title: "Pick up kids", description: "Kindergarten closes at 5pm", }; todoInfo; // const todoInfo: TodoInfo
Exclude
用于构造一个类型,它是从UnionType
联合类型里面,排除所有ExcludedMembers
类型。
type T0 = Exclude; // type T0 = "b" | "c" type T1 = Exclude; // type T1 = "c" type T2 = Exclude void), Function>; // type T2 = string | number
Extract
用于构造一个类型,它是从Type
类型里面,提取所有Union
类型。
type T0 = Extract; // type T0 = "a" type T1 = Extract void), Function>; // type T1 = () => void
NonNullable
用于构造一个类型,从Type
中,排除所有的null
、undefined
类型。
type T0 = NonNullable; // type T0 = string | number type T1 = NonNullable; // type T1 = string[]
Parameters
根据所有Type
中,函数的参数类型,构造一个元组类型。
type T0 = Parameters string>; // type T0 = [] type T1 = Parameters void>; // type T1 = [s: string] type T2 = Parameters T>; // type T2 = [arg: unknown]
declare function f1(arg: { a: number; b: string }): void; type T3 = Parameters; /* type T3 = [arg: { a: number; b: string; }] */ type T4 = Parameters; // type T4 = unknown[] type T5 = Parameters; // type T5 = never type T6 = Parameters; // TypeError: Type 'string' does not satisfy the constraint '(...args: any) => any'.// type T6 = never type T7 = Parameters; // TypeError: Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.// type T7 = never
ConstructorParameters
根据Type
中,构造函数类型,来构造一个元组或数组类型。它产生一个带着所有参数类型的元组。如果Type
不是一个函数,则返回never
。
在 TypeScript 标准库中,内置有构造签名的实际构造函数:interface ErrorConstructor
、interface FunctionConstructor
、interface RegExpConstructor
类型。
type T0 = ConstructorParameters; // type T0 = [message?: string] type T1 = ConstructorParameters; // type T1 = string[] type T2 = ConstructorParameters; // type T2 = [pattern: string | RegExp, flags?: string] type T3 = ConstructorParameters; // type T3 = unknown[] type T4 = ConstructorParameters; // TypeError: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.// type T4 = never
ReturnType
用于构造一个由Type
中函数的返回值的类型,组成的类型。
type T0 = ReturnType string>; // type T0 = string type T1 = ReturnType void>; // type T1 = void type T2 = ReturnType T>; // type T2 = unknown type T3 = ReturnType T>; // type T3 = number[]
declare function f1(): { a: number; b: string }; type T4 = ReturnType; /* type T4 = { a: number; b: string; } */ type T5 = ReturnType; // type T5 = any type T6 = ReturnType; // type T6 = never type T7 = ReturnType; // TypeError: Type 'string' does not satisfy the constraint '(...args: any) => any'.// type T7 = any type T8 = ReturnType; // TypeError: Type 'Function' does not satisfy the constraint '(...args: any) => any'. Type 'Function' provides no match for the signature '(...args: any): any'.// type T8 = any
InstanceType
用于构造一个由所有Type
中构造函数的实例类型,组成的类型。
class C { x = 0; y = 0; } type T0 = InstanceType; // type T0 = C type T1 = InstanceType; // type T1 = any type T2 = InstanceType; // type T2 = never type T3 = InstanceType; // TypeError: Type 'string' does not satisfy the constraint 'abstract new (...args: any) => any'.// type T3 = any type T4 = InstanceType; // TypeError: Type 'Function' does not satisfy the constraint 'abstract new (...args: any) => any'. Type 'Function' provides no match for the signature 'new (...args: any): any'.// type T4 = any
ThisParameterType
用于提取函数的this
参数的类型。如果这个函数没有this
参数,则返回unknown
类型。
function toHex(this: Number) { return this.toString(16); } function numberToString(n: ThisParameterType) { return toHex.apply(n); // (parameter) n: number }
OmitThisParameter
用于移除函数的this
参数的类型。如果Type
没有明确的声明this
类型,那么这个返回的结果就是Type
,不然的话,就返回一个新的函数类型,基于Type
,但不再有this
参数。泛型会被抹去,只有最后重载的签名被传播进了返回的新的函数类型。
function toHex(this: Number) { return this.toString(16); } const fiveToHex: OmitThisParameter = toHex.bind(5); console.log(fiveToHex());
ThisType
这个类型不返回一个转换过的类型,它被用作标记一个上下文的this
类型。注意:如果想使用这个工具类型,noImplicitThis
选项,必须启用。
type ObjectDescriptor = { data?: D; methods?: M & ThisType; // Type of 'this' in methods is D & M }; function makeObject(desc: ObjectDescriptor): D & M { let data: object = desc.data || {}; let methods: object = desc.methods || {}; return { ...data, ...methods } as D & M; } let obj = makeObject({ data: { x: 0, y: 0 }, methods: { moveBy(dx: number, dy: number) { this.x += dx; // Strongly typed this this.y += dy; // Strongly typed this }, }, }); obj.x = 10; obj.y = 20; obj.moveBy(5, 5);
在上面的例子中,makeObject
函数的参数重methods
对象有上下文的类型包含了ThisType
,因此methods
方法中的this
类型是{x: number, y: number}&{moveBy(dx: number, dy: number): number}
。注意methods
的类型是怎么同时成为一个接口的目标和方法中this
类型的源。
ThisType
标记的接口是一个生命在lib.d.ts
中的简单的空接口。除了被认为是一个对象字面量的上下文类型,这个接口表现得就像一个空接口。
内置字符操作类型
Uppercase
Lowercase
Capitalize
Uncapitalize
为了帮助围绕模版字符串的字符串处理,TypeScript 的类型系统包含了一系列中可以用于字符串操作的类型。你可以在文档模板字面量类型中找到这些。
鹏仔微信 15129739599 鹏仔QQ344225443 鹏仔前端 pjxi.com 共享博客 sharedbk.com
图片声明:本站部分配图来自网络。本站只作为美观性配图使用,无任何非法侵犯第三方意图,一切解释权归图片著作权方,本站不承担任何责任。如有恶意碰瓷者,必当奉陪到底严惩不贷!