I'm trying to create a Overwrite
type that can overwrite an existing type's properties with a different type. For instance:
type TypeA = { prop1: string; prop2: number };
type OverwrittenType = Overwrite<TypeA, { prop1: number; prop2: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: string }
I found this SO answer which does the job nicely, however it's a bit too permissive for my liking, as it allows you to replace properties that were never in the original type to begin with.
type TypeA = { prop1: string; prop2: number };
type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>;
// OverwrittenType is now equivalent to { prop1: number; prop2: number; prop3: string }
Below is the Overwrite
type from that other thread.
type Overwrite<T, U> = Pick<T, Exclude<keyof T, keyof U>> & U;
How do I need to modify it to prohibit replacement keys that are not present in the initial type?
type TypeA = { prop1: string; prop2: number };
type OverwrittenType = Overwrite<TypeA, { prop1: number; prop3: string }>; // Throw some sort of error here, prop3 is not a key of TypeA