I am rather new to typescript and are trying to assign the correct types to my JS files. While doing so, I am trying to write as view boilerplate as possible and so I stumbled over this:
I receive compilation errors only under specific conditions. As soon as I call the array filter method after line 14, it starts failing to compile but doesn't fail at line 17.
Why does it fail when calling filter and why does it not fail in line 17?
interface A {
iAm: 'a';
}
interface B {
iAm: 'b';
}
interface C {
iAm: string;
}
const fails: (A|B)[] = [{iAm: 'a'}, {iAm: 'b'}]
.filter(() => true);
const works: (B|C)[] = [{iAm: 'b'}, {iAm: 'c'}]
.filter(() => true);
Error:
const fails: (A | B)[]
Type '{ iAm: string; }[]' is not assignable to type '(A | B)[]'.
Type '{ iAm: string; }' is not assignable to type 'A | B'.
Type '{ iAm: string; }' is not assignable to type 'B'.
Types of property 'iAm' are incompatible.
Type 'string' is not assignable to type '"b"'.(2322)
stringunless there is a local hint to do otherwise; I'd suggest using aconstassertion as shown here. Does that address the question fully? If so I'll write up an answer explaining; otherwise, what am I missing?