'TypeScript omit shared base keys from combined type with hardcoded values
I'm trying to create a type that has all possible keys from multiple other types, plus some extra but excluding another (shared) base type.
The problem is that some of the keys have hard set values, when intersecting these types it unfortunately results in type never. How do I go about getting a type that has all possible keys?
type Base = {
base: string;
};
type A = Base & {
type: 1;
};
type B = Base & {
type: 2;
notShared: string;
optional?: string;
};
type New = Omit<A & B, keyof Base> & {
extra: string;
};
// Unfortunately equivalent to:
// type New = Omit<never, keyof Base> & {
// extra: string;
// }
const test: New = {
extra: '',
type: 1, // Should allow 1 or 2
notShared: '',
optional: '',
q: '', // Should not allow
base: '', // Should not allow
};
Solution 1:[1]
I solved it like this but I have the feeling there might be a shorter way:
type New = {
[K in Exclude<keyof A | keyof B, keyof Base>]:
K extends keyof A ?
K extends keyof B ?
B[K] | A[K] : A[K]
: B[K]
} & {
extra: string
}
const test: New = {
extra: '',
type: 1,
notShared: '',
optional: "",
base: '', // error
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tobias S. |
