I'd like to create a generic mapped type in TypeScript with the following concepts:
- Allows any writable key from the base type to be set to a value (same type as in the base type) or a pre-defined flag
- Allows readonly keys to be set ONLY to the pre-defined flag.
Here is a non-working example of the concept:
type KindOfMutable1<T> = {
-readonly[P in keyof T]?: "FLAG";
} | { // THIS DOES NOT WORK
[P in keyof T]?: T[P] | "FLAG"
};
interface thingy {
x: number;
readonly v: number;
}
const thing1: KindOfMutable1<thingy> = {x: 1};
thing1.v = "FLAG";
// ^ ERROR HERE: Cannot assign to 'v' because it is a read-only property
Another way to think about my desired solution would look something like this:
// pseudo code of a concept:
type KindOfMutable2<T> = {
[P in keyof T]?: /* is T[P] readonly */ ? "FLAG" : T[P] | "FLAG"
};
Is there any way to do this?