I am a novice in the realm of generics. Although the code snippets for "w0" and "w1" appear to be identical, they actually have different purposes and types.
Could someone shed light on why they are distinct from each other, and also provide guidance on achieving the opposite type interchangeably?
Despite extensively searching through various documents, I have yet to come across a comprehensive explanation. Does anyone know of a resource that delves into the underlying principles behind their varied types?
Is there a way to achieve
Calc<BaseA> | Calc<BaseB>
without explicitly invoking Calc
or Generics
?
How can I create
{ type: "A" | "B"; flag: number; }
utilizing the power of Generics
?
type BaseA = {
type: 'A'
name: string
flag: number
}
type BaseB = {
type: 'B'
id: number
flag: number
}
type Base = BaseA | BaseB
type w0 = {
[k in keyof Base]: Base[k]
}
/*
w0 = {
type: "A" | "B";
flag: number;
}
*/
type Calc<W> = {
[k in keyof W]: W[k]
}
type w1 = Calc<Base>
/*
w1 = Calc<BaseA> | Calc<BaseB>
*/
type z0 = Exclude<w0,BaseA>
// z0 = w0
type z1 = Exclude<w1,BaseA>
// z1 = BaseB