ts-Utility Types(高级类型)
Partial
将泛型传入的T中所有属性转换为可选属性,返回的类型可以是T的任意子集。
// 源码
type Partial<T> = {
[P in keyof T]?: T[P];
};
Required
将泛型传入的T中所有属性转换为必须属性,和Partial类型相反。
type Required<T> = {
[P in keyof T]-?: T[P];
};
Readonly
将泛型传入的T中所有属性转换为只读属性。
type Readonly<T> = {
readonly [P in keyof T]: T[P];
};
Record<K, T>
创建一个对象类型,使对象的键key的类型为传入的泛型K,使对象的值value的类型为传入的泛型T。
type Record<K extends keyof any, T> = {
[P in K]: T;
};
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>
Pick<T, K>
通过传入的泛型T中选择一组属性K(字符串字面值或字符串字面值的联合)来构造类型。规定了泛型K必须是泛型T中key的子集。
type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
interface Todo {
title: string;
description: string;
completed: boolean;
}
// 相当于type TodoPreview = { title: string; completed: boolean; }
type TodoPreview = Pick<Todo, "title" | "completed">;
const todo: TodoPreview = {
title: "Clean room",
completed: false,
};
Omit<T,K>
通过传入的泛型T中选择一组属性K并删除其他属性,和Pick相反。
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;
Exclude<UnionType, ExcludedMembers>
排除某些type
type T0 = Exclude<"a" | "b" | "c", "a">;
// type T0 = "b" | "c"
Extract<Type, Union>
两个type的交集
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// type T0 = "a"
NonNullable
从type中排除null、undefined。
Parameters
获取一个函数里面参数的类型,不过注意是用元组的形式获取。
type T1 = Parameters<(s: string) => void>;
type T1 = [s: string]
ConstructorParameters
从构造函数类型的类型构造元组或数组类型。它生成一个包含所有参数类型的元组类型(如果 Type 不是函数,则生成类型never)。
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[]
type T4 = ConstructorParameters<Function>;
// 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
获取函数中的返回值类型
InstanceType
获取类实例的类型
ThisParameterType
提取函数类型的 this 参数的类型,如果函数类型没有此参数,则为unknow。
OmitThisParameter
移除,和ThisParameterType相反
ThisType
不返回转换后的类型。相反,它充当上下文类型的标志。请注意,必须启用 noImplicitThis 标志才能使用此。
Intrinsic String Manipulation Types
-
Uppercase<StringType>
-
Lowercase
-
Capitalize
-
Uncapitalize