Typescript:映射类型,使除所选属性之外的每个属性均为只读

Geo*_*43g 2 types typescript mapped-types

我遇到了一个挑战,我不想继续重写多个接口。

我需要一个完全可写的接口,并且还需要该接口的“副本”,其中除我选择可写的字段外,所有字段都是只读的。

Typescript 具有可以允许此操作的映射类型。

Geo*_*43g 5

export type DeepReadOnly<T> = { readonly [key in keyof T]: DeepReadOnly<T[key]> };
export type DeepMutable<T> = { -readonly [key in keyof T]: DeepMutable<T[key]> };
export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
export type DeepKeepMutable<T, K extends keyof T> = DeepReadOnly<Omit<T, K>> & DeepMutable<Pick<T, K>>;

// use as follows
let o: DeepKeepMutable<Metadata, 'time' | 'payload'>;
// this will keep time and payload writeable while the rest are readonly

// it is also possible to extend and modify these types with index signatures, optional properties and level of depth

Run Code Online (Sandbox Code Playgroud)