dwn
dwn

Reputation: 413

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

i.e. 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.

Upvotes: 2

Views: 650

Answers (2)

Jose Greinch
Jose Greinch

Reputation: 458

If you check https://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

Upvotes: 0

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250376

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.

Upvotes: 6

Related Questions