TS 内置工具

本文详细介绍了TypeScript的内置工具类型,包括Record、Partial、Readonly、Pick、Exclude、NonNullable、Parameters、ConstructorParameters、ReturnType、InstanceType和Omit,以及非内置类型DeepReadonly、ConvertNumberToString、ValueOf和Mutable的使用方法和示例。这些工具类型在处理复杂类型时非常有用,如转换属性可选性、排除特定属性、获取函数参数和返回类型等。

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

TS 内置工具

1、Record -> 生产一个属性为K,类型为T的类型集合。

type React<K entends keyof any, T> = {
[P in K]: T;
}
用法
type Foo = Record<‘a’, string> // 相当于 type Foo = { a: string }
type Bar = {
b: string
}
type Baz = Record< keyof Foo | keyof Bar, number > // typ Baz = { a: number, b: number }
注解:可以用于创建 也可以用于合并然后重新赋值。 感觉没什么用

2、Partial-> 全部变可选 - 相反 Required -> 全部必选

type Partial = {
[P in keyof T]?: T[P];
};
用法
type IFoo = {
a?: string,
b: string
}
const foo: Partial = { a: ‘1’ } // 变为可选
const bar: Required<Partial> = { // 变为全部必选
a: ‘1’,
b: ‘2’
}

3、Readonly -> 全部只读 字面意思

type Readonly = {
readonly [P in keyof T]: T[P];
};
用法
type IFoo = {
name: string;
age: number;
}
const foo: Readonly = {
name: ‘cxc’,
age: 22,
}
foo.name = ‘xiaoming’ // 错误,因为 name 仅是只读的
foo.age = 20 // 错误,因为 age 也仅是只读的

4、Pick-> 提取一个属性

type Pick<T, K extends keyof T> = {
[P in K]: T[P];
};
用法
type IFoo = {
name: string;
age: number;
}
const foo: Pick<IFoo, ‘name’> = { // 相当于 type IFoo = { name: string }
name: ‘name’
}
const ifoo: Pick<IFoo, ‘name’ | ‘age’ | ‘msg’ > = { // 取出多个
name: ‘222’,
age: 1,
msg: ‘success’
}

5、Exclude-> 从 T 中排除掉所有包含的 U 属性 -> 相反 Extract 提取 T 和 U 都有的

type Exclude<T, U> = T extends U ? never : T;
用法
type TFoo = Exclude<string | number | boolean, number> // 相当于 type IFoo = string | boolean
type XFoo = Exclude<string | number | boolean, number | string> // 相当于 type IFoo = string | number
const foo: TFoo = ‘2’ // 正确
const foo: TFoo = false // 正确
const foo: TFoo = 2 // 错误
const foo: XFoo = ‘2’ | 2 // 都正确
注释: 去除 T 中 U有的。 和 提取 T U都有的

6、NonNullable-> 去除 null 和 underfined

type NonNullable = T extends null | undefined ? never : T;
用法
type TFoo = 1 | null | undefined
let foo: TFoo = 1
foo = null
foo = undefined
let foo: NonNullable = 1 // 正确
foo = null // 错误,因为这个值已经被去除
foo = undefined// 错误,因为这个值已经被去除

7、Parameters-> 传入一个函数 返回 函数的参数数组

type Parameters<T extends (…args: any[]) => any> = T extends (…args: infer P) => any ? P : never;
用法
type Func = (a: string, b: number) => void
type Param = Parameters // 相当于 type Param = [string, number]

8、ConstructorParameters-> 传入一个类 返回 类的构造函数参数数组

type ConstructorParameters<T extends new (…args: any[]) => any> = T extends new (…args: infer P) => any ? P : never;
用法
class Foo {
constructor(x: string, y: number) {
console.log(x, y)
}
}
const foo: ConstructorParameters = [‘1’, 2]; // 相当于 type foo = [string, number]

9、ReturnType-> 传入一个函数 返回 函数的返回类型

type ReturnType<T extends (…args: any[]) => any> = T extends (…args: any[]) => infer R ? R : any;
用法
type Func = (value: number) => string
const foo: ReturnType = ‘1’

10、InstanceType-> 传入一个函数 返回 函数的返回类型

type InstanceType<T extends new (…args: any[]) => any> = T extends new (…args: any[]) => infer R ? R : any;
用法
class Foo {
public x = ‘1’
public y = 2
public say = (value: string) => {
console.log(value)
}
}
const foo: InstanceType = {
x: ‘1’,
y: 2,
say: (value: string) => {
console.log(value)
}
}
// 相当于
// type Foo = {
// x: string,
// y: number,
// say: (value: string) => void
// }
注释: 上边的7、8、9、10都是从函数和类中获取它们的各种类型参数

11、Omit-> 忽略T 中的 K属性

type User = { id: string; name: string; email: string;};
type UserWithoutEmail = Omit<User, “email”>;// This is equivalent to:
type UserWithoutEmail = { id: string; name: string;};
相当于删除了其中的属性

非内置类型定义
1、DeepReadonly-> 深度遍历 并把属性变成只读

type DeepReadonly = { readonly [P in keyof T]: DeepReadonly<T[P]> }
同上面的Readonly 一样,一个是浅层的 一个是深层的。
type Foo = {
a: string,
b: {
c: string,
}
}
const foo: DeepReadonly = {
a: ‘1’,
b: {
c: ‘2’,
}
}
foo.b.c = ‘s’; // c 为只读

2、ConvertnumberToString-> 将number转化成string

type ConvertNumberToString = {
[K in keyof T]: T[K] extends string ? string : T[K]
}

3、ValueOf -> 同 keyof 的 取出所有属性名, ValueOf是取出所有value裂隙

type ValueOf = T[keyof T]
用法
type Foo = {
a: string;
num: number;
}
type Valuea = ValueOf // string | number

4、Mutable-> 去除所有只读

type Mutable = {
-readonly [P in keyof T]: T[P]
}

总结

大部分的内置方法感觉都用不到,常用的应该是
Partial、Exclude、Pick,像其他全部转化的内置工具,太过于绝对。

<think>好的,用户想了解TypeScript中的内置工具类型,我需要先回忆一下相关知识。根据用户提供的引用内容,引用2和4提到了Partial、Required、Pick、Omit、InstanceType等工具类型。用户可能希望了解这些内置类型的用途和用法。首先,我需要列出常见的工具类型,比如Partial、Required、Readonly、Record、Pick、Omit、Exclude、Extract、ReturnType、InstanceType等。然后,针对每个类型给出具体的示例,帮助用户理解它们的应用场景。要注意引用中的例子,比如Partial<User>将所有属性变为可选,Required<User>变为必填。引用4还提到了InstanceType用于获取类实例的类型。需要确保每个工具类型的说明都清晰,并配合代码示例。另外,用户可能想知道如何在实际开发中应用这些工具类型,比如在定义React组件props或处理API响应数据时使用Partial或Omit。需要结合实际场景举例,增强实用性。需要检查是否有遗漏的工具类型,比如ThisType<T>,但根据引用4,可能用户更关注常用的那些。同时,注意引用3提到掌握内置类型能提升效率,所以应强调这些工具类型的重要性。最后,生成相关问题时要围绕工具类型的应用、组合使用、实际案例以及与其他TypeScript特性的结合。确保问题能引导用户进一步深入学习。</think>### TypeScript内置工具类型使用说明 TypeScript内置工具类型通过**泛型编程**简化类型操作,提升代码复用性和可维护性。以下是常见工具类型的分类解析: --- #### 一、属性操作类 1. **`Partial<T>`** 将类型`T`的所有属性变为**可选**: ```typescript interface User { id: number; name: string } type PartialUser = Partial<User>; // { id?: number; name?: string } ``` 2. **`Required<T>`** 将类型`T`的所有属性变为**必填**: ```typescript type RequiredUser = Required<PartialUser>; // 恢复为原User类型 ``` 3. **`Readonly<T>`** 将类型`T`的所有属性变为**只读**: ```typescript type ReadonlyUser = Readonly<User>; // { readonly id: number; readonly name: string } ``` --- #### 二、结构操作类 4. **`Pick<T, K>`** 从类型`T`中**选取指定属性**`K`(联合类型): ```typescript type UserName = Pick<User, "name">; // { name: string } ``` 5. **`Omit<T, K>`** 从类型`T`中**排除指定属性**`K`: ```typescript type UserWithoutId = Omit<User, "id">; // { name: string } ``` 6. **`Record<K, V>`** 创建键为`K`、值为`V`的**对象类型**: ```typescript type UserMap = Record<"admin" | "guest", User>; // { admin: User; guest: User } ``` --- #### 三、类型关系类 7. **`Exclude<T, U>`** 从联合类型`T`中**排除**属于`U`的类型: ```typescript type T = Exclude<"a" | "b" | "c", "a">; // "b" | "c" ``` 8. **`Extract<T, U>`** 从联合类型`T`中**提取**属于`U`的类型: ```typescript type T = Extract<"a" | "b" | 1, string>; // "a" | "b" ``` --- #### 四、函数与类操作类 9. **`ReturnType<T>`** 获取函数类型`T`的**返回值类型**: ```typescript type FnReturn = ReturnType<() => string>; // string ``` 10. **`Parameters<T>`** 获取函数类型`T`的**参数类型元组**: ```typescript type FnParams = Parameters<(a: number, b: string) => void>; // [number, string] ``` 11. **`InstanceType<T>`** 获取构造函数类型`T`的**实例类型**: ```typescript class MyClass {} type MyInstance = InstanceType<typeof MyClass>; // MyClass ``` --- #### 五、组合应用示例 **场景:动态表单配置** ```typescript interface FormConfig { fields: Partial<Pick<User, "name" | "email">>; onSubmit: (data: Required<User>) => void; } ``` --- ### 相关问题 1. 如何通过`Omit`和`Pick`实现嵌套对象属性的类型操作? 2. `ThisType<T>`工具类型的具体使用场景是什么[^4]? 3. 如何在React组件中结合`Partial`和`Readonly`优化Props类型? 4. TypeScript工具类型与条件类型(Conditional Types)如何配合使用?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值