Skip to content

Add a Mutable type (opposite of Readonly) to lib.d.ts #24509

Description

@selmanj

Search Terms

mutable, mutable type

Suggestion

lib.d.ts contains a Readonly type, but not a Mutable type. This type would be the opposite of Readonly, defined as:

type Mutable<T> = {
  -readonly[P in keyof T]: T[P]
};

Use Cases

This is useful as a lightweight builder for a type with readonly properties (especially useful when some of the properties are optional and conditional logic is needed before assignment).

Examples

 type Mutable<T> = {-readonly[P in keyof T]: T[P]};
 
 interface Foobar {
   readonly a: number;
   readonly b: number;
   readonly x?: string;
 }

 function newFoobar(baz: string): Foobar {
   const foobar: Mutable<Foobar> = {a: 1, b: 2};
   if (shouldHaveAnX(baz)) {
     foobar.x = 'someValue';
   }

   return foobar;
 }

Checklist

My suggestion meets these guidelines:

  • This wouldn't be a breaking change in existing TypeScript / JavaScript code
  • This wouldn't change the runtime behavior of existing JavaScript code
  • This could be implemented without emitting different JS based on the types of the expressions
  • This isn't a runtime feature (e.g. new expression-level syntax)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Awaiting More FeedbackThis means we'd like to hear from more people who would be helped by this featureSuggestionAn idea for TypeScript

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions