返回
TypeScript 一些你可能不知道的工具泛型使用及其实现
前端
2024-02-03 21:09:01
Partial
Partial
interface Person {
name: string;
age: number;
}
const partialPerson: Partial<Person> = {
name: 'Alice',
};
Required
Required
interface Person {
name: string;
age?: number;
}
const requiredPerson: Required<Person> = {
name: 'Alice',
age: 25,
};
Readonly
Readonly
interface Person {
name: string;
age: number;
}
const readonlyPerson: Readonly<Person> = {
name: 'Alice',
age: 25,
};
readonlyPerson.name = 'Bob'; // Error: Cannot assign to read-only property 'name'
Record
Record<K, V> 创建一个以 K 为键类型、V 为值类型的对象类型。
type KeyValue<T> = Record<string, T>;
const person: KeyValue<string> = {
name: 'Alice',
age: '25',
};
Pick
Pick<T, K> 从 T 中选取具有指定键 K 的属性,创建一个新的类型。
interface Person {
name: string;
age: number;
address: string;
}
type PersonName = Pick<Person, 'name'>;
const personName: PersonName = {
name: 'Alice',
};
Omit
Omit<T, K> 从 T 中排除具有指定键 K 的属性,创建一个新的类型。
interface Person {
name: string;
age: number;
address: string;
}
type PersonWithoutAddress = Omit<Person, 'address'>;
const personWithoutAddress: PersonWithoutAddress = {
name: 'Alice',
age: 25,
};
Exclude
Exclude<T, U> 从 T 中排除 U 中的类型,创建一个新的类型。
type Primitive = string | number | boolean;
type NonPrimitive = Exclude<any, Primitive>;
// NonPrimitive 等于 object | Function | symbol
Extract
Extract<T, U> 从 T 中提取 U 中的类型,创建一个新的类型。
type Primitive = string | number | boolean;
type NonPrimitive = Extract<any, Primitive>;
// NonPrimitive 等于 never
NonNullable
NonNullable
type Person = {
name: string | null;
age: number | undefined;
};
type NonNullablePerson = NonNullable<Person>;
const nonNullablePerson: NonNullablePerson = {
name: 'Alice',
age: 25,
};
Parameters
Parameters
function sum(a: number, b: number): number {
return a + b;
}
type SumParameters = Parameters<typeof sum>;
// SumParameters 等于 [number, number]
ConstructorParameters
ConstructorParameters
class Person {
constructor(name: string, age: number) {}
}
type PersonConstructorParameters = ConstructorParameters<typeof Person>;
// PersonConstructorParameters 等于 [string, number]
ReturnType
ReturnType
function sum(a: number, b: number): number {
return a + b;
}
type SumReturnType = ReturnType<typeof sum>;
// SumReturnType 等于 number
InstanceType
InstanceType
class Person {
constructor(name: string, age: number) {}
}
type PersonInstance = InstanceType<typeof Person>;
// PersonInstance 等于 Person
通过使用这些工具泛型,我们可以更轻松地编写类型安全的 TypeScript 代码,并创建更加健壮和可维护的应用程序。