简体   繁体   中英

Typescript mapped types

It is recommended to use mapped types over explicitly partial types, see https://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types

ie instead of

interface PersonPartial {
    name?: string;
    age?: number;
}

we'd use

interface Person {
    name: string;
    age: number;
}
type Partial<T> = {
    [P in keyof T]?: T[P];
}
type PersonPartial = Partial<Person>;

Is it possible to map into the other direction, something like

type NotPartial<T> = {
    [P in keyof T]!: T[P];
}
type Person = NotPartial<PersonPartial>;

as I have a generated that creates partial interfaces, which break my type checking due to duck typing.

You can use the -? syntax to remove the ? from a homomorphic mapped type (but keep reading) :

interface Person {
    name?: string;
    age?: number;
}
type Mandatory<T> = {
    [P in keyof T]-?: T[P];
}
type PersonMandatory = Mandatory<Person>;

Example on the playground . This is described here .

But , you don't have to, because TypeScript already has it: Required<T> . Required<T> ...

...strips ? modifiers from all properties of T , thus making all properties required.

So:

interface Person {
    name?: string;
    age?: number;
}
type RequiredPerson = Required<Person>;

Example on the playground .

If you checkhttps://www.typescriptlang.org/docs/handbook/utility-types.html you can see that Typescript provides a lot of Utility Types. So please that the Utility is not there already. You can find Required is best suited for your scenario.

If you want to know more I wrote an article about mapped types here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM