TS常用内置的工具类型有,Record、Readonly、Required、Partial、Extract、Exclude、Pick、Omit、NonNullable、Parameters、ReturnType。记住这些,在开发中,将会提高我们的开发效率。
目录
Record
Readonly
Required
Partial
Exclude
Pick
Omit
NonNullable
Parameters
ReturnType
Record
| type Record<K extends string | number | symbol, T> = { |
| [P in K]: T; |
| } |
| |
| Record<key type, value type> |
复制
- 它的作用是将对象所有的属性都转化为需要的类型。将对象所有的属性的值转化为T类型,用Record<K extends keyof any,T>。我们可以用Record将各属性都变成字符类型,然后就可以直接赋值给下面的变量使用了
| type Property = 'u1' | 'u2' |
| type User = Record<Property,string>; |
| |
| const u:User = { |
| u1:"xiaom", |
| u2:"zhans", |
| } |
复制
Readonly
| interface U{ |
| name:string; |
| age:number; |
| gender?:"male" | "female"; |
| } |
| |
| let c:Readonly<U> = { |
| name:"xiaom", |
| age:10, |
| gender:"male", |
| }; |
| |
| c.age = 190 |
复制
Required
| ReturnType<T extends (...args: any) => any> |
复制
| interface U { |
| name?:string, |
| age?:number, |
| gender?:string[] |
| } |
| |
| |
| |
| |
| |
| const c:Required<U> = { |
| name:"xiaom" |
| age:20, |
| gender:["male"] |
| } |
复制
Partial
| type Partial<T> = { |
| [P in keyof T]?: Partial<T[P]> |
| } |
复制
| interface U{ |
| name:string, |
| age:number |
| } |
| |
| |
| |
| const c:U = { |
| name:'xiaom' |
| } |
| |
| |
| const c:Partial<U> = { |
| name:'xiaom' |
| } |
复制
| type Extract<T, U> = T extends U ? T : never |
复制
- 它的作用是提取联合类型中某些类型,用Extract<T,U>,表示从T中提取出U。
| |
| type U = Extract<string | number | (() => void), Function>; |
复制
Exclude
| type Exclude<T, U> = T extends U ? never : T |
复制
- 它的作用是移除联合类型中某些类型,用Exclude<T,U>,表示从T中移除U
| |
| type U = Exclude<"string" | "number" | "boolean","number">; |
复制
Pick
| |
| |
| type U = { |
| name:string, |
| age:number, |
| gender:string |
| } |
| |
| |
| |
| |
| type c = Pick<U,"age" | "gender">; |
| |
| |
| |
| const u1:c = { |
| age:30, |
| gender:'xxxx' |
| } |
复制
Omit
| type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>> |
复制
- 它的作用是从类型中移除一些类型,Omit<T,U>从T中取出除去U的其它所有属性
| |
| |
| type U = { |
| name:string, |
| age:number, |
| gender:string |
| } |
| |
| |
| |
| |
| type U = Omit<User,"age" | "gender"> |
| |
| |
| |
| const c:U = { |
| name:'xiaom' |
| } |
复制
NonNullable
NonNullable: 它的作用是去除类型中的null和undefined
| |
| type u = NonNullable<string[] | null | undefined>; |
复制
Parameters
| Parameters<T extends (...args: any) => any> |
复制
| |
| type u = Parameters<(a:number,b:string) => void>; |
复制
ReturnType
| ReturnType<T extends (...args: any) => any> |
复制
| |
| type fun = (value:string) => string; |
| const u:ReturnType<fun> = 'xiaom' |
复制