bbdb500951c28ce4b321ee6891a1af8e3022549b80ea0221b4dc0f3b561d78f622d37821189849b27bc0ca928bb200e4a1f5b5734b128c456ee9018fabe2f4 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import {Except} from './except';
  2. import {Simplify} from './simplify';
  3. /**
  4. Create a type that strips `readonly` from all or some of an object's keys. Inverse of `Readonly<T>`.
  5. This can be used to [store and mutate options within a class](https://github.com/sindresorhus/pageres/blob/4a5d05fca19a5fbd2f53842cbf3eb7b1b63bddd2/source/index.ts#L72), [edit `readonly` objects within tests](https://stackoverflow.com/questions/50703834), [construct a `readonly` object within a function](https://github.com/Microsoft/TypeScript/issues/24509), or to define a single model where the only thing that changes is whether or not some of the keys are mutable.
  6. @example
  7. ```
  8. import {Mutable} from 'type-fest';
  9. type Foo = {
  10. readonly a: number;
  11. readonly b: readonly string[]; // To show that only the mutability status of the properties, not their values, are affected.
  12. readonly c: boolean;
  13. };
  14. const mutableFoo: Mutable<Foo> = {a: 1, b: ['2']};
  15. mutableFoo.a = 3;
  16. mutableFoo.b[0] = 'new value'; // Will still fail as the value of property "b" is still a readonly type.
  17. mutableFoo.b = ['something']; // Will work as the "b" property itself is no longer readonly.
  18. type SomeMutable = Mutable<Foo, 'b' | 'c'>;
  19. // type SomeMutable = {
  20. // readonly a: number;
  21. // b: readonly string[]; // It's now mutable. The type of the property remains unaffected.
  22. // c: boolean; // It's now mutable.
  23. // }
  24. ```
  25. */
  26. export type Mutable<BaseType, Keys extends keyof BaseType = keyof BaseType> =
  27. Simplify<
  28. // Pick just the keys that are not mutable from the base type.
  29. Except<BaseType, Keys> &
  30. // Pick the keys that should be mutable from the base type and make them mutable by removing the `readonly` modifier from the key.
  31. {-readonly [KeyType in keyof Pick<BaseType, Keys>]: Pick<BaseType, Keys>[KeyType]}
  32. >;