What Does "-?" Mean in TypeScript?

Introduced in TypeScript 2.8, if the ? modifier is prefixed with - (i.e. -?), it means that the ? modifier is removed from a mapped type, making all properties required.

If the ? modifier has no + or - prefix, then it is the same as if the ? modifier was prefixed with + (i.e. +?).

For example, using "-?", the Required utility type can be implemented like so:

type Required<Type> = { [Property in keyof Type]-?: Type[Property] };

This maps all keys of type "Type" and makes them required.

You can, of course, make use of -? in various other ways. Consider for example the following, where the custom utility type takes all the properties from the type "Type" and changes their values to be required and be of type string:

// TypeScript 2.8+
type RequestBody<Type> = {
    [Property in keyof Type]-?: string;
};

This could, for instance, be used like so:

// TypeScript 2.8+
type Patient = {
    name: string;
    age?: number;
    recovered?: boolean;
};

type PatientRequestBody = RequestBody<Patient>;

const patient: PatientRequestBody = {
    name: 'John Doe',
    age: '23',
    recovered: 'false',
};

If any property from the "Patient" type is missing or a value is not of type string, this would throw an error:

// TypeScript 2.8+
// Error: Property 'recovered' is missing in type '{ name: string; age: string; }' but required in type 'RequestBody<Patient>'.
const patient: PatientRequestBody = {
    name: 'John Doe',
    age: '23',
};
// TypeScript 2.8+
const patient: PatientRequestBody = {
    name: 'John Doe',
    age: '23',
    // Error: Type 'boolean' is not assignable to type 'string'.
    recovered: false,
};

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.