typescript 补充
文章目录
- Pick<T, K> 从 T 中挑选部分属性构成新类型
- Partial<T>:将类型的所有属性变为可选
- Required<T>:将类型的属性变为必选。
- Omit<T, K>:从 T 中移除部分属性构成新类型。
- Readonly<T>:将类型的属性设为只读。
- Record<string | number | symbol,any>
- 类型推断
- 数组的不可变性 (ReadonlyArray)
- 深度不可变 DeepReadonly
Pick<T, K> 从 T 中挑选部分属性构成新类型
interface Person {
name: string;
age: number;
email?: string;
}
type PickedPerson = Pick<Person, "name" | "age">; // { name: string; age: number }
const person: PickedPerson = {
age: 20,
name: "Tom",
};
Partial:将类型的所有属性变为可选
interface IProps {
name: string;
age: number;
sex: "男" | "女";
job?: string;
}
type Person2 = Partial<IProps>; // { name?: string; age?: number; sex?: "男" | "女"; job?: string }
const person2: Person2 = {
name: "Tom",
sex: "男",
};
Required:将类型的属性变为必选。
interface IProps {
name: string;
age: number;
sex: "男" | "女";
job?: string;
}
type Person3 = Required<IProps>; // { name: string; age: number; sex: "男" | "女"; job: string }
const person3: Person3 = {
name: "Tom",
age: 20,
sex: "男",
job: "程序员",
};
Omit<T, K>:从 T 中移除部分属性构成新类型。
interface IProps {
name: string;
age: number;
sex: "男" | "女";
job?: string;
}
type Person6 = Omit<IProps, "sex" | "name">; // { age: number; job?: string }
const person6 : Person6 = {
age: 20,
job: "程序员",
}
Readonly:将类型的属性设为只读。
interface IProps {
name: string;
age: number;
sex: "男" | "女";
job?: string;
}
type Person4 = Readonly<IProps>;
const person4: Person4 = {
name: "Tom",
age: 20,
sex: '男',
}
// person4.name = "Jerry"; // 会报错,因为name是只读的
Record<string | number | symbol,any>
Record<string | number | symbol,any> 是一个类型工具,用于创建一个对象类型,其中键的类型可以选三种 ,值的类型可以任意规定
interface IProps {
name: string;
age: number;
sex: "男" | "女";
job?: string;
}
type Person = Pick<IProps, "name" | "age">;
const person5: Record<string, Person> = {
Tom: {
name: "Tom",
age: 20,
},
Jerry: {
name: "Jerry",
age: 22,
},
}
类型推断
ReturnType 是返回函数的返回值的类型
Parameters 是返回参数的类型
type Func = (x: number, y: string) => boolean;
type ReturnTypeOfFunc = ReturnType<Func>; // boolean
type ParametersOfFunc = Parameters<Func>; // [number, string]
数组的不可变性 (ReadonlyArray)
ReadonlyArray 是 readonly 在数组中的一种特例。与普通数组不同,ReadonlyArray 禁止使用会修改数组的方法(例如 push、pop 等),从而确保数组内容不会被改变。
const numbers: ReadonlyArray<number> = [1, 2, 3];
// numbers.push(4); // 错误:ReadonlyArray 不允许修改数组内容
深度不可变 DeepReadonly
仅将嵌套对象设为不可变,而让顶层的普通属性保持可变状态
type DeepReadonly<T> = {
[K in keyof T]: T[K] extends object ? Readonly<T[K]> : T[K];
};
interface PersonA {
name: string;
address: { city: string; zip: string };
}
const person7: DeepReadonly<PersonA> = {
name: "Alice",
address: { city: "New York", zip: "10001" },
};
person7.name = "Bob";
// person7.address.city = "Boston" // Error