前端必知必会-TypeScript 实用类型

文章目录

  • TypeScript 实用类型
    • Partial
    • required
    • Record
    • 省略Omit
    • Pick
    • Exclude
    • ReturnType
    • 参数Parameters
    • Readonly
  • 总结


TypeScript 实用类型

TypeScript 附带大量类型,可帮助进行一些常见的类型操作,通常称为实用类型。

Partial

Partial 将对象中的所有属性更改为可选。

示例

interface Point {
x: number;
y: number;
}

let pointPart: Partial<Point> = {}; // `Partial` 允许 x 和 y 为可选
pointPart.x = 10;

required

Required 将对象中的所有属性更改为必需。

示例

interface Car {
make: string;
model: string;
mileage?: number;
}

let myCar:Required<Car> = {
make: 'Ford',
model: 'Focus',
mileage: 12000 // `Required` 强制定义里程
};

Record

Record是定义具有特定键类型和值类型的对象类型的快捷方式。

示例

const nameAgeMap: Record<string, number> = {
'Alice': 21,
'Bob': 25
};

Record 相当于 { [key: string]: number }

省略Omit

省略Omit从对象类型中删除键。

示例

interface Person {
name: string;
age: number;
location?: string;
}

const bob: Omit<Person, 'age' | 'location'> = {
name: 'Bob'
// `Omit` 已从类型中删除 age 和 location,因此无法在此处定义它们
};

Pick

Pick 从对象类型中删除除指定键之外的所有键。

示例

interface Person {
name: string;
age: number;
location?: string;
}

const bob: Pick<Person, 'name'> = {
name: 'Bob'
// `Pick` 仅保留了 name,因此 age 和 location 已从类型中删除,因此无法在此处定义它们
};

Exclude

Exclude 从联合中删除类型。

示例

type Primitive = string | number | boolean
const value: Exclude<Primitive, string> = true; // 字符串无法在此处使用,因为 Exclude 已将其从类型中删除。

ReturnType

ReturnType 提取函数类型的返回类型。

示例

type PointGenerator = () => { x: number; y: number; };
const point: ReturnType<PointGenerator> = {
x: 10,
y: 20
};

参数Parameters

参数Parameters将函数类型的参数类型提取为数组。

示例

type PointPrinter = (p: { x: number; y: number; }) => void;
const point: Parameters<PointPrinter>[0] = {
x: 10,
y: 20
};

Readonly

Readonly 用于创建一个新类型,其中所有属性都是只读的,这意味着一旦赋值,它们就不能被修改。

请记住,TypeScript 会在编译时阻止这种情况,但理论上,由于它被编译为 JavaScript,因此您仍然可以覆盖只读属性。

示例

interface Person {
name: string;
age: number;
}
const person: Readonly<Person> = {
name: "Dylan",
age: 35,
};
person.name = 'Israel'; // prog.ts(11,8): 错误 TS2540: 无法分配给“name”,因为它是只读属性。

总结

本文介绍了TypeScript 实用类型的使用,如有问题欢迎私信和评论

你可能感兴趣的:(前端,typescript,ubuntu)