Reputation: 501
I have an array that contains objects of different types. I learned from the documentation that TypeScript can deduce union types such as string | number
and number | number[]
based on the code structure, but it can't seem to deal with more complex interfaces.
interface A {
type: string;
a: string;
}
interface B {
type: string;
b: string;
}
const a: A = { type: 'a', a: 'foo'};
const b: B = { type: 'b', b: 'bar'};
const arr = [a, b];
arr.forEach((item) => {
if (item.type === 'a') {
console.log(item.a); // Property 'a' does not exist on type 'A | B'.
}
else if (item.type === 'b') {
console.log(item.b); // Property 'b' does not exist on type 'A | B'.
}
});
What's the best practice in this case? Is it okay to just cast the item to the expected type in each block?
Upvotes: 0
Views: 331
Reputation: 169
To improve that a little bit more, you can add to @Evert solution the following:
enum Types{
a,
b}
interface A{
type:Types.a;
a:string
}
interface B{
type:Types.b
b:string
}
This can be useful to avoid spelling mistakes.
Upvotes: 1
Reputation: 99581
Is it possible you just need to adjust your types a bit:
interface A {
type: 'a';
a: string;
}
interface B {
type: 'b';
b: string;
}
Upvotes: 3