TS 内置工具类使用笔记

ts内置工具类笔记

ReturnType 获取函数返回值类型

type EditorStore = ReturnType<typeof func>

Partial 将T的所有属性改为可选属性

type PartialT = Partial<T>

Required 将T的所有属性变为必须属性

type RequireT = Required<T>

Readonly 将T的所有属性改为只读属性,赋值后无法修改

type Readonly = Readonly<T>

Pick 从T中选取一组属性K来构造一个新类型

type Pick = Readonly<T,K>

Omit 从T中剔除一组属性K来构造一个新类型

type OmitK = Omit<T,K>

Exclude 从T中剔除可以赋值给K的类型,返回剩余的类型

type AllColors = 'red' | 'blue' | 'green' | 'yellow';
type PrimaryColors = 'red' | 'blue' | 'yellow';

type SecondaryColors = Exclude<AllColors, PrimaryColors>;

// SecondaryColors 类型为 'green'

Extract<T, U> 从T中提取可以赋值给U的类型

type AllNumbers = 1 | 2 | 3 | 4 | 5;
type EvenNumbers = 2 | 4;

type ExtractedEvenNumbers = Extract<AllNumbers, EvenNumbers>;

// ExtractedEvenNumbers 类型为 2 | 4

NonNullable 从T中排除null 和 undefined类型

type MaybeString = string | null | undefined;

type DefiniteString = NonNullable<MaybeString>;

// DefiniteString 类型为 string

InstanceType InstanceType 获取构造函数类型T的实例类型

class User {
    constructor(public name: string, public age: number) {}
}

type UserInstance = InstanceType<typeof User>;

// UserInstance 类型为 { name: string; age: number; }
posted @ 2025-03-19 11:42  lence  阅读(43)  评论(0)    收藏  举报