目录
一、与对象相关的工具类
1、Partial<type>
(1)含义:将type的所有类型设置为可选
(2)示例:
interface ITest1{
name:string
age:number
}
type ITest2 = Partial<ITest1>
ITest2相当于
interface ITest2{
name?:string
age?:number
}
2、Required<type>
(1)含义:构建一个类型,使类型Type
的所有属性为required
。 与此相反的是Partial
(2)使用:
interface Props {
a?: number;
b?: string;
}
const obj: Props = { a: 5 }; // OK
const obj2: Required<Props> = { a: 5 }; // Error: property 'b' missing
3、Readonly<type>
(1)含义:类型里面的属性都无法再被赋值
(2)使用:
interface ITode {
title: string
}
const a: Readonly<ITode> = {
title: 'xxxx',
}
a.title = 'jjjj' //报错,title为只读属性
4、 Record<keys,type>
(1)含义:用来将某个类型的属性映射到另一个类型上。
const type1 = {'key':{type2}}
type1类型里面的value值都是type2类型的时候适用。
(2)使用:
interface AValue {
name?: string
age?: number
}
type AKey = 'people1' | 'people2'
type A = Record<AKey, AValue>
const human: A = {
people1: {
name: '2',
age: 2,
},
people2: {
name: '3',
},
}
A类型的值类型都是AValue类型,常规写法相当于:
interface AValue {
name?: string
age?: number
}
type A = {
people1: AValue
people2: AValue
people3: AValue
}
const human: A = {
people1: {
name: '2',
age: 2,
},
people2: {
name: '3',
},
people3: {
age: 2,
},
}
interface AValue {
name?: string
age?: number
}
type A = Record<string, AValue>
const human: A = {
people1: {
name: '2',
age: 2,
},
}
这样写不必非要有people1和people2两个key值
5、 Pick<type,keys>
(1)含义:从类型Type
中挑选部分属性Keys
来构造类型。key of type,key必须是type里面的。
(2)使用:
interface People1 {
name: string
age: number
children: number
}
type People2 = Pick<People1, 'name' | 'age'>
const a: People2 = {
name: '1',
age: 2,
}
6、Omit<type,keys>
(1)含义:从类型Type
中获取所有属性,然后从中剔除Keys
属性后构造一个类型。key of type,key必须是type里面的。
(2)使用:
interface Todo {
title: string;
description: string;
completed: boolean;
}
type TodoPreview = Omit<Todo, 'description'>;
const todo: TodoPreview = {
title: 'Clean room',
completed: false,
};
二、与类型有关的工具类
1、Exclude<type,excludedUnion>
(1)含义:从类型Type
中剔除所有可以赋值给ExcludedUnion
的属性,然后构造一个类型。
(2)使用:
type T0 = Exclude<'a' | 'b' | 'c', 'a'>; // "b" | "c"
type T1 = Exclude<'a' | 'b' | 'c', 'a' | 'b'>; // "c"
type T2 = Exclude<string | number | (() => void), Function>; // string | number
2、Extract<Type, Union>
(1)含义:从类型Type
中提取所有可以赋值给Union
的类型,然后构造一个类型。
(2)使用:
type T0 = Extract<'a' | 'b' | 'c', 'a' | 'f'>; // "a"
type T1 = Extract<string | number | (() => void), Function>; // () => void
3、NonNullable<type>
(1)含义:非空的,从类型Type
中剔除null
和undefined
,然后构造一个类型。
(2)使用:
type T0 = NonNullable<string | number | undefined>; // string | number
type T1 = NonNullable<string[] | null | undefined>; // string[]
三、与函数相关的工具类
使用的频率较低,待有空时补充。