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 added to a mapped type, making all properties optional.

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 Partial utility type can be implemented like so:

type Partial<Type> = { [Property in keyof Type]+?: Type[Property] };

This is the same as the following:

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

These types map all keys of type "Type" and make them optional.

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 optional and makes them readonly:

// TypeScript 2.8+
type ReadonlyPartial<T> = {
    readonly [P in keyof T]+?: T[P]
};

This could, for instance, be used like so:

// TypeScript 2.8+
type Todo = {
    title: string;
    description: string;
};

type ArchivedTodo = ReadonlyPartial<Todo>;

const task1: ArchivedTodo = { title: 'Do the dishes' };

The "ArchivedTodo" type in this example, makes all properties of the "Todo" type optional and readonly, which means that if you try to (re)assign any property, it would throw an error:

// ...
// Error: Cannot assign to 'description' because it is a read-only property.
task1.description = 'Make them squeaky clean';

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