TypeScript 附带了大量类型,可以帮助进行一些常见的类型操作,通常称为实用程序类型。
本章涵盖最流行的实用程序类型。
Partial
将对象中的所有属性更改为可选。
interface Point {
x: number;
y: number;
}
let pointPart: Partial<Point> = {}; // `Partial` allows x and y to be optional
pointPart.x = 10;
亲自试一试 »
Required
更改对象中所需的所有属性。
interface Car {
make: string;
model: string;
mileage?: number;
}
let myCar: Required<Car> = {
make: 'Ford',
model: 'Focus',
mileage: 12000 // `Required` forces mileage to be defined
};
亲自试一试 »
Record
是使用特定键类型和值类型定义对象类型的快捷方式。
Record<string, number>
相当于{ [key: string]: number }
Omit
从对象类型中删除键。
interface Person {
name: string;
age: number;
location?: string;
}
const bob: Omit<Person, 'age' | 'location'> = {
name: 'Bob'
// `Omit` has removed age and location from the type and they can't be defined here
};
亲自试一试 »
Pick
从对象类型中删除除指定键之外的所有键。
interface Person {
name: string;
age: number;
location?: string;
}
const bob: Pick<Person, 'name'> = {
name: 'Bob'
// `Pick` has only kept name, so age and location were removed from the type and they can't be defined here
};
亲自试一试 »
Exclude
从联合中删除类型。
type Primitive = string | number | boolean
const value: Exclude<Primitive, string> = true; // a string cannot be used here since Exclude removed it from the type.
亲自试一试 »
ReturnType
提取函数类型的返回类型。
type PointGenerator = () => { x: number; y: number; };
const point: ReturnType<PointGenerator> = {
x: 10,
y: 20
};
亲自试一试 »
Parameters
将函数类型的参数类型提取为数组。
type PointPrinter = (p: { x: number; y: number; }) => void;
const point: Parameters<PointPrinter>[0] = {
x: 10,
y: 20
};
亲自试一试 »
Readonly
用于创建一个新类型,其中所有属性都是只读的,这意味着它们一旦赋值就无法修改。
请记住,TypeScript 会在编译时阻止这种情况,但理论上,由于它被编译为 JavaScript,您仍然可以覆盖只读属性。
interface Person {
name: string;
age: number;
}
const person: Readonly
= {
name: "Dylan",
age: 35,
};
person.name = 'Israel'; // prog.ts(11,8): error TS2540: Cannot assign to 'name' because it is a read-only property.
亲自试一试 »