Typescript 映射类型

dwn*_*dwn 2 typescript mapped-types

建议使用映射类型而不是显式部分类型,请参阅 https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types

即代替

interface PersonPartial {
    name?: string;
    age?: number;
}
Run Code Online (Sandbox Code Playgroud)

我们会用

interface Person {
    name: string;
    age: number;
}
type Partial<T> = {
    [P in keyof T]?: T[P];
}
type PersonPartial = Partial<Person>;
Run Code Online (Sandbox Code Playgroud)

是否可以映射到另一个方向,例如

type NotPartial<T> = {
    [P in keyof T]!: T[P];
}
type Person = NotPartial<PersonPartial>;
Run Code Online (Sandbox Code Playgroud)

因为我有一个生成的部分接口,这会由于鸭子类型而破坏我的类型检查。

Tit*_*mir 6

您可以使用语法从同态映射类型中-?删除(但请继续阅读)?

interface Person {
    name?: string;
    age?: number;
}
type Mandatory<T> = {
    [P in keyof T]-?: T[P];
}
type PersonMandatory = Mandatory<Person>;
Run Code Online (Sandbox Code Playgroud)

操场上的例子此处对此进行了描述。

但是,您不必这样做,因为 TypeScript 已经有了它:Required<T>Required<T>...

...?从 的所有属性中删除修饰符T,从而使所有属性成为必需的。

所以:

interface Person {
    name?: string;
    age?: number;
}
type RequiredPerson = Required<Person>;
Run Code Online (Sandbox Code Playgroud)

操场上的例子

  • @TJCrowder 文档?!这是打字稿。真正的打字稿开发人员阅读所有 PR(https://github.com/Microsoft/TypeScript/pull/21919)和所有问题(并且不起作用,因为这是一份全职工作)。 (2认同)