UNPKG

1.07 kBTypeScriptView Raw
1import type {Except} from './except';
2import type {Simplify} from './simplify';
3
4/**
5Create a type that makes the given keys readonly. The remaining keys are kept as is.
6
7Use-case: You want to define a single model where the only thing that changes is whether or not some of the keys are readonly.
8
9@example
10```
11import type {SetReadonly} from 'type-fest';
12
13type Foo = {
14 a: number;
15 readonly b: string;
16 c: boolean;
17}
18
19type SomeReadonly = SetReadonly<Foo, 'b' | 'c'>;
20// type SomeReadonly = {
21// a: number;
22// readonly b: string; // Was already readonly and still is.
23// readonly c: boolean; // Is now readonly.
24// }
25```
26
27@category Object
28*/
29export type SetReadonly<BaseType, Keys extends keyof BaseType> =
30 // `extends unknown` is always going to be the case and is used to convert any
31 // union into a [distributive conditional
32 // type](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html#distributive-conditional-types).
33 BaseType extends unknown
34 ? Simplify<
35 Except<BaseType, Keys> &
36 Readonly<Pick<BaseType, Keys>>
37 >
38 : never;