What Does "-?" Mean in TypeScript?

Find out what "-?" refers to 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.

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

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

This merely 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 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,
};

Hope you found this post useful. It was published . Please show your love and support by sharing this post.