一、`Omit`
作用:根据现有类型创建一个新的类型,去除不需要的特定属性。
现在我们想要一个新的类型,它与 `Person` 类型相同,但不包含 `address` 属性。可以使用 `Omit` 来实现
interface Person {
name: string;
age: number;
address: string;
phone: string;
}
type PersonWithoutAddress = Omit<Person, "address">;
const personWithoutAddress: PersonWithoutAddress = {
name: "John",
age: 30,
phone: "1234567890",
};
二、`Pick`
作用:从一个类型中挑选出一组属性,创建一个新的类型。
interface Person {
name: string;
age: number;
address: string;
}
type PersonNameAndAge = Pick<Person, "name" | "age">;
const personNameAndAge: PersonNameAndAge = {
name: "John",
age: 30,
};
三、`Partial`
作用:将一个类型的所有属性变为可选的,创建一个新的类型。
interface Person {
name: string;
age: number;
address: string;
}
type PartialPerson = Partial<Person>;
const partialPerson: PartialPerson = {
name: "John",
};
四、`Required`
作用:将一个类型的所有属性变为必填的,创建一个新的类型。
interface Person {
name?: string;
age?: number;
address?: string;
}
type RequiredPerson = Required<Person>;
const requiredPerson: RequiredPerson = {
name: "John",
age: 30,
address: "Somewhere",
};
五、`Readonly`
作用:将一个类型的所有属性变为只读的,创建一个新的类型。
interface Person {
name: string;
age: number;
}
type ReadonlyPerson = Readonly<Person>;
const readonlyPerson: ReadonlyPerson = {
name: "John",
age: 30,
};
// 尝试修改会报错
readonlyPerson.name = "Jane";
六、`Record`
作用:创建一个由指定键类型和值类型组成的对象类型。
type Key = string;
type Value = number;
type MyRecord = Record<Key, Value>;
const myRecord: MyRecord = {
key1: 10,
key2: 20,
};
七、`Exclude<T, U>`
作用:从类型 `T` 中排除可以赋值给类型 `U` 的类型,返回一个新的类型。
type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
八、`Extract<T, U>`
作用:从类型 `T` 中提取可以赋值给类型 `U` 的类型,返回一个新的类型。
type T2 = Extract<"a" | "b" | "c", "a" | "b">; // "a" | "b"
九、`NonNullable<T>`
作用:从类型 `T` 中排除 `null` 和 `undefined`,返回一个新的类型。
type T3 = NonNullable<string | null | undefined>; // string
十、`ReturnType<T>`
作用:获取函数类型 `T` 的返回值类型。
type T4 = ReturnType<() => string>; // string
十一、`Parameters<T>`
作用:获取函数类型 `T` 的参数类型组成的元组类型。
type T5 = Parameters<(a: number, b: string) => void>; // [number, string]
十二、`InstanceType<T>`
作用:获取构造函数类型 `T` 的实例类型。
class MyClass {
prop = "value";
}
type T6 = InstanceType<typeof MyClass>; // MyClass 的实例类型

被折叠的 条评论
为什么被折叠?



