Review this TypeScript snippet:
class A {public name: string = 'A';}
interface B {num: number;}
class Foo {
get mixed(): Array<A | B> {
const result = [];
for (var i = 0; i < 100; i ++) {
result.push(Math.random() > 0.5 ? new A() : {num: 42});
}
return result;
}
print(): string {
return this.mixed.map(item => {
if (item instanceof A) {
return item.name;
}
return item.num;
}).join('\n');
}
}
In the print
method, different values need to be returned based on the type of item
. While it's easy to use instanceof
for type A
, the use of B
as an interface makes it challenging.
TypeScript may not recognize that item
is definitely of type
B</code when accessing <code>item.num
, leading to unnecessary complaints.