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.
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 ofT
, thus making all properties required.
So:
interface Person {
name?: string;
age?: number;
}
type RequiredPerson = Required<Person>;