typescripttypescript2.2

Forcing a type's fields to not be optional


Given a type with optional properties, including a nested reference to another type with optional properties (such as itself):

type Foo = {
    fieldA?: string,
    fieldB?: number,
    fieldDeep?: Foo,
};

is there a way to produce a version of that type with all properties now non-optional:

type RequiredFoo = {
    fieldA: string,
    fieldB: number,
    fieldDeep: RequiredFoo,
};

This type would essentially be the reverse of a deep form of Partial, which is doable:

type DeepPartial<T> = {
    [P in keyof T]?: DeepPartial<T[P]>
};

I figured out a strange trick do this shallow-ly for instances of a type:

function required<T>(obj: Partial<T>): { [P in keyof T]: T[P] } {
    return obj as any;
} 

const requiredFoo: {
    fieldA: string,
    fieldB: number,
    fieldDeep: Foo,
} = required({} as Foo);

but I can't find a way to express this type recursively, mainly because I cannot express the function above as an actual type definition---the reason it works at all is because of the obj: Partial<T> parameter, perhaps because it infers that any optional parameters are due to obj being Partial, rather than because of the object itself.


Solution

  • This is now expressible using the Required<T> built-in:

    type DeepRequired<T> = Required<{ [P in keyof T]: DeepRequired<T[P]> }>;