Sometimes you want to take a type and remove certain special words (modifiers) from its properties. This helps make the type simpler or change how it behaves.
0
0
Removing modifiers with minus in Typescript
Introduction
When you want to make all properties of an object writable instead of readonly.
When you want to remove optional marks from properties to make them required.
When you want to create a new type based on another but without some special property rules.
When you want to control how strict or loose your types are in different parts of your code.
Syntax
Typescript
type NewType = { -readonly [K in keyof OldType]: OldType[K] };
type AnotherType = { -? [K in keyof OldType]: OldType[K] };The minus sign - before readonly or ? removes that modifier from the type.
This syntax is used inside mapped types to change property modifiers.
Examples
This removes
readonly and ? (optional) from all properties, making them writable and required.Typescript
type ReadonlyUser = {
readonly name: string;
readonly age?: number;
};
type WritableUser = {
-readonly [K in keyof ReadonlyUser]-?: ReadonlyUser[K];
};This removes the
? optional modifier, making all properties required.Typescript
type OptionalUser = {
name: string;
age?: number;
};
type RequiredUser = {
[K in keyof OptionalUser]-?: OptionalUser[K];
};This removes only the
readonly modifier, keeping optional properties as they are.Typescript
type ReadonlyUser = {
readonly name: string;
age: number;
};
type WritableUser = {
-readonly [K in keyof ReadonlyUser]: ReadonlyUser[K];
};Sample Program
This example shows how to remove both readonly and ? from properties. The new type EditablePerson has writable and required properties.
Typescript
type ReadonlyPerson = {
readonly id: number;
readonly name?: string;
};
type EditablePerson = {
-readonly [K in keyof ReadonlyPerson]-?: ReadonlyPerson[K];
};
const person: EditablePerson = {
id: 1,
name: "Alice"
};
// person.id = 2; // This works because 'readonly' is removed
// person.name = undefined; // Not allowed because '?' is removed
console.log(person);OutputSuccess
Important Notes
Removing modifiers only works inside mapped types using [K in keyof T] syntax.
Using -readonly removes the readonly modifier, making properties writable.
Using -? removes the optional modifier, making properties required.
Summary
You can remove readonly and ? modifiers using a minus sign - in mapped types.
This helps create new types with different property rules based on existing types.
It is useful for controlling mutability and optionality in your TypeScript types.