Take a moment to explore the following example:
type Num = {
type: 'NUMBER'
numberValue: number
}
type Str = {
type: 'STRING',
stringValue: string
}
type B_Num = {
a: Num;
numberData: number;
}
type B_Str = {
a: Str;
stringData: string;
}
type A = Num | Str
type B = B_Num | B_Str
function test_Num(num: Num) {}
function test_B_Num(bNum: B_Num) {}
function test_B(b: B) {
if (b.a.type === 'NUMBER') {
test_Num(b.a) // Recognizes b.a as Num
test_B_Num(b) // Struggles to recognize b as B_Num (typing error occurs)
}
}
Check out the code in action here.
Have you ever wondered why typescript
struggles to identify the specific type of variable b
? Even though it has the necessary information (recognizing b as B
and b.a as Num
).