泛型工具类型 1 Partial type所有属性变成可选
interface Props{
id:number,
name:string
}
type PartialProps = Partial<Props>
使用后 PartialProps里的所有属性都变成可选 即:
type PartialProps = {
id?: number | undefined;
name?: string | undefined;
}
泛型工具类型 2 Readonly 讲type的所有属性都设置成只读的
interface Props{
id:number,
name:string
}
type ReadonlyProps = Readonly<Props>
let props : ReadonlyProps = {id:1,name:'xxx'}
// props.name='w3f' 这句话 此时会报错
使用Readonly后,对象里面的属性只可读,不可以改变。此时ReadonlyProps为:
type ReadonlyProps = {
readonly id: number;
readonly name: string;
}
泛型工具类型 3 Pick<type,key> 从type中选择一组属性 来构造新类型
//两个变量表示:1)表示谁的属性 2)表示选择哪一个属性,此属性只能是前面第一个变量传入的类型变量中的属性
interface Props2{
id:number,
name:string,
age:number
}
type PickProps = Pick<Props2,'id'|'age'> //这表示 构造出来的新类型PickProps 只有id age两个属性类型
表示在旧的类型中选择一部分属性,讲选择的属性来重新构造成一个新的类型。此时PickProps为:
type PickProps = {
id: number;
age: number;
}
泛型工具类型 4 Record<keys,type> 构造一个对象类型,属性键为keys,属性类型为type
//两个变量表示:1)表示对象有哪些属性 2)表示对象属性的类型
type RecordObj = Record<'a'|'b'|'c',string> //此处表示 此类型变量有a b c三个键,并且三个的属性值都是string类型
let obj :RecordObj = {
a:'1',
b:'2',
c:'3'
}
type RecordObj = {
a: string;
b: string;
c: string;
}