ts Utility Types笔记

本文详细介绍了JavaScript中的 Partial、Required、Readonly等类型操作技巧,包括Pick、Record、Exclude、Extract、Omit和NonNullable,帮助开发者理解和利用这些工具优化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Utility Types

1.Partial

/**
 * 设置T类型中所有属性为可选的
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};
// 原类型
interface Props {
  title: string;
  description: string;
}
type PartalProps = Partial<Props>
// 转换后类型相当于
type PartalProps = {
  title?: string;
  description?: string;
}

2. Required

/**
 * 设置类型T中所有属性为必填的
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};
// 原类型
interface Props {
  title?: string;
  description?: string;
}
type RequiredProps = Required<Props>
// 转换后类型相当于
type RequiredProps = {
  title: string;
  description: string;
}

3. Readonly

/**
 * 设置类型T中所有属性为只读的
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};
// 原类型
interface Props {
  title: string;
  description: string;
}
type RequiredProps = Required<Props>
// 转换后类型相当于
type RequiredProps = {
  readonly title: string;
  readonly description: string;
}
// 示例
const todo: Readonly<Props> = {
  title: "title",
};
todo.title = "Hello"; // 报错 

4. Pick

/**
 * 从类型T中,选择一组key在K中的属性
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};
interface Props {
  title: string;
  description: string;
  completed: boolean;
}
 
type PickProps = Pick<Props, "title" | "completed">;
 // 转换后类型相当于
type PickProps = {
  title: string;
  completed: boolean;
}
// 示例
const todo: PickProps = {
  title: "Clean room",
  completed: false,
};

5. Record

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};
// 原类型
interface Props {
  age: number;
  breed: string;
}
 
type PropsTypes = "miffy" | "boris";
type RecordProps = Record<PropsTypes, Props>
  // 转换后类型相当于
type RecordProps = {
  miffy: Props;
  boris: Props;
}
// 示例
const cats: Record<PropsTypes, Props> = {
  miffy: { age: 10, breed: "Persian" },
  boris: { age: 5, breed: "Maine Coon" },
};


6. Exclude

/**
 * 通过从 并集T 中排除可分配给 并集U 的所有联合成员
 */
type Exclude<T, U> = T extends U ? never : T;
// 示例1
type T0 = Exclude<"a" | "b" | "c", "a">;
// 相当于
type T0 = "b" | "c"

// 示例2
type T1 = Exclude<"a" | "b" | "c", "a" | "b">;
// 相当于
type T1 = "c"

// 示例3
type T2 = Exclude<string | number | (() => void), Function>;   
// 相当于
type T2 = string | number

7. Extract

/**
 * 从并集 T 中提取可分配给 并集U 的所有联合成员
 */
type Extract<T, U> = T extends U ? T : never;
// 示例1
type T0 = Extract<"a" | "b" | "c", "a" | "f">;
// 相当于
type T0 = "a"

// 示例2
type T1 = Extract<string | number | (() => void), Function>;
 // 相当于    
type T1 = () => void

8. Omit

/**
 * 从类型T中,排除K中的键
 */
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

interface Props {
  title: string;
  description: string;
  completed: boolean;
  createdAt: number;
}
 
type OmitProps = Omit<Props, "description" | "createdAt">;
// 转换后类型相当于
type OmitProps = {
	title: string;
	completed: boolean;
}
// 示例
const todo: TodoPreview = {
  title: "Clean room",
  completed: false,
};

9. NonNullable

/**
 * 从类型T中,排除null and undefined
 */
type NonNullable<T> = T extends null | undefined ? never : T;
// 示例1
type T0 = NonNullable<string | number | undefined>;
// 相当于
type T0 = string | number

// 示例1
type T1 = NonNullable<string[] | null | undefined>;
// 相当于
type T1 = string[]

10. Parameters

/**
 * 从函数的参数中使用的类型 构造元组类型
 */
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any ? P : never;


 // 示例1
type T0 = Parameters<() => string>;
// 相当于
type T0 = []

// 示例2
type T1 = Parameters<(s: string) => void>;
// 相当于
type T1 = [s: string]

// 示例3
type T2 = Parameters<<T>(arg: T) => T>;
// 相当于
type T2 = [arg: unknown]

// 示例4
declare function f1(arg: { a: number; b: string }): void;
type T3 = Parameters<typeof f1>;
// 相当于 
type T3 = [arg: {
    a: number;
    b: string;
}]

// 示例5
type T4 = Parameters<any>;
// 相当于  
type T4 = unknown[]

// 示例6
type T5 = Parameters<never>;
// 相当于  
type T5 = never

11. ConstructorParameters


/**
 * 从构造函数的参数 构造
 */
type ConstructorParameters<T extends abstract new (...args: any) => any> = T extends abstract new (...args: infer P) => any ? P : never;
// 示例1
interface Error {
    name: string;
    message: string;
    stack?: string;
}
interface ErrorConstructor {
    new(message?: string): Error;
    (message?: string): Error;
    readonly prototype: Error;
}
type T0 = ConstructorParameters<ErrorConstructor>;
// 相当于
type T0 = [message?: string]

// 示例2
interface FunctionConstructor {
    /**
     * Creates a new function.
     * @param args A list of arguments the function accepts.
     */
    new(...args: string[]): Function;
    (...args: string[]): Function;
    readonly prototype: Function;
}
type T1 = ConstructorParameters<FunctionConstructor>;
// 相当于
type T1 = string[]

// 示例3
interface RegExpConstructor {
    new(pattern: RegExp | string): RegExp;
    new(pattern: string, flags?: string): RegExp;
    (pattern: RegExp | string): RegExp;
    (pattern: string, flags?: string): RegExp;
    readonly prototype: RegExp;

    // Non-standard extensions
    /** @deprecated A legacy feature for browser compatibility */
    $1: string;
    /** @deprecated A legacy feature for browser compatibility */
    $2: string;
    /** @deprecated A legacy feature for browser compatibility */
    $3: string;
    /** @deprecated A legacy feature for browser compatibility */
    $4: string;
    /** @deprecated A legacy feature for browser compatibility */
    $5: string;
    /** @deprecated A legacy feature for browser compatibility */
    $6: string;
    /** @deprecated A legacy feature for browser compatibility */
    $7: string;
    /** @deprecated A legacy feature for browser compatibility */
    $8: string;
    /** @deprecated A legacy feature for browser compatibility */
    $9: string;
    /** @deprecated A legacy feature for browser compatibility */
    input: string;
    /** @deprecated A legacy feature for browser compatibility */
    $_: string;
    /** @deprecated A legacy feature for browser compatibility */
    lastMatch: string;
    /** @deprecated A legacy feature for browser compatibility */
    "$&": string;
    /** @deprecated A legacy feature for browser compatibility */
    lastParen: string;
    /** @deprecated A legacy feature for browser compatibility */
    "$+": string;
    /** @deprecated A legacy feature for browser compatibility */
    leftContext: string;
    /** @deprecated A legacy feature for browser compatibility */
    "$`": string;
    /** @deprecated A legacy feature for browser compatibility */
    rightContext: string;
    /** @deprecated A legacy feature for browser compatibility */
    "$'": string;
}
type T2 = ConstructorParameters<RegExpConstructor>;
// 相当于
type T2 = [pattern: string | RegExp, flags?: string]

// 示例4
type T3 = ConstructorParameters<any>;
// 相当于
type T3 = unknown[]

12. ReturnType

/**
 * 获取 函数的返回类型
 */
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

// 示例1
type T0 = ReturnType<() => string>;
// 相当于
type T0 = string

// 示例2
type T1 = ReturnType<(s: string) => void>;
// 相当于
type T1 = void

// 示例3
type T2 = ReturnType<<T>() => T>;
// 相当于
type T2 = unknown

// 示例4
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
// 相当于
type T3 = number[]

// 示例5
declare function f1(): { a: number; b: string };
type T4 = ReturnType<typeof f1>;
// 相当于
type T4 = {
    a: number;
    b: string;
}

// 示例6
type T5 = ReturnType<any>;
// 相当于
type T5 = any

// 示例7
type T6 = ReturnType<never>;
// 相当于
type T6 = never

13. InstanceType

/**
 * 获取 构造函数的返回类型
 */
type InstanceType<T extends abstract new (...args: any) => any> = T extends abstract new (...args: any) => infer R ? R : any;

// 示例1
class C {
  x = 0;
  y = 0;
}
type T0 = InstanceType<typeof C>;
// 相当于     
type T0 = C

// 示例2
type T1 = InstanceType<any>;
相当于
type T1 = any

// 示例
type T2 = InstanceType<never>;
相当于
type T2 = never

14. Uppercase

/**
 * 将字符串文字类型转换为大写
 */
type Uppercase<S extends string> = intrinsic;

// 示例1
type Greeting = "Hello, world"
type ShoutyGreeting = Uppercase<Greeting>
相当于
type ShoutyGreeting = "HELLO, WORLD"
 
 // 示例2
type ASCIICacheKey<Str extends string> = `ID-${Uppercase<Str>}`
type MainID = ASCIICacheKey<"my_app">
// 相当于
type MainID = "ID-MY_APP"

15. Lowercase

/**
 * 将字符串文字类型转换为小写
 */
type Lowercase<S extends string> = intrinsic;

// 示例1
type Greeting = "Hello, world"
type QuietGreeting = Lowercase<Greeting>
// 相当于
type QuietGreeting = "hello, world"
 
 // 示例2
type ASCIICacheKey<Str extends string> = `id-${Lowercase<Str>}`
type MainID = ASCIICacheKey<"MY_APP">
// 相当于
type MainID = "id-my_app"

16. Capitalize

/**
 * 将字符串文字类型的第一个字符转换为大写
 */
type Capitalize<S extends string> = intrinsic;

type LowercaseGreeting = "hello, world";
type Greeting = Capitalize<LowercaseGreeting>;
// 相当于
type Greeting = "Hello, world"

17. Uncapitalize

/**
 * 将字符串文字类型的第一个字符转换为小写
 */
type Uncapitalize<S extends string> = intrinsic;

type UppercaseGreeting = "HELLO WORLD";
type UncomfortableGreeting = Uncapitalize<UppercaseGreeting>;
// 相当于 
type UncomfortableGreeting = "hELLO WORLD"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值