制作 TypeScript 所需的所有属性

制作 TypeScript 所需的所有属性

Make all properties required in TypeScript

使用Required实用程序类型使类型中的所有属性成为必需的,例如const emp: Required<Employee> = {}.

实用程序类型构造一个新类型,其中提供的Required类型的所有属性都设置为必需。

索引.ts
interface Employee { id?: number; name?: string; salary?: number; } const emp: Required<Employee> = { id: 1, name: 'Tom', salary: 1000, };

我们使用
Required
实用程序类型来构造一个新类型,其中所提供类型的所有属性都设置为必需。

索引.ts
interface Employee { id?: number; name?: string; salary?: number; } // 👇️ type T = { // id: number; // name: string; // salary: number; // } type T = Required<Employee>;

Required您可以在 TypeScript 的
Github 存储库中看到内置类型是如何实现的

索引.ts
/** * Make all properties in T required */ type Required<T> = { [P in keyof T]-?: T[P]; };

The -?: syntax is called a
mapping modifier
and is used to affect optionality.

When prefixed with a minus, the mapping modifier removes the optionality of the
type’s properties.

The utility type basically takes all of the properties of the provided type and removes their optionality (makes them required).

Mapping modifiers can affect optionality both ways, e.g. you can also use them
to make all of the properties of a type optional by prefixing the ?: with a
plus (+?:).

If you don’t add a prefix, then + is assumed.

index.ts
/** * Make all properties in T optional */ type Partial<T> = { [P in keyof T]?: T[P]; };

This is the
code
for the Partial utility type, which makes all of the properties in a type
optional.

请注意,这两种类型之间的唯一区别是类型中问号前面的减号Required

-?:语法删除了可选性,而?:(or +?:) 使类型中的所有属性都是可选的。