I'm assuming this is intentional behavior, but it's unexpected. Given the following:
interface Foo {
foo: number
}
interface Bar {
bar: Foo
}
const BAR = 'bar'
const BAR2: string = 'bar'
function getBar(bar: Bar): boolean {
return bar[BAR].foo // error, typescript can discern the value of `BAR` and reports that `number` is not assignable to `boolean`.
}
function getBar2(bar: Bar): boolean {
return bar[BAR2].foo // typescript appears to not be able to discern the value of `BAR2`
}
I would have expected Typescript to be abel to discern the value of BAR2 and thus, be able to discern the type and error on an invalid function return type like getBar is doing. But it appears Typescript only knows that BAR2 is a string.
NB: turning on noImplicitAny will expose a different error on getBar2 because there's no index signature on Bar
Can someone please shed some light on why the explicit typing on a const results in this behavior?
foodoes not have the right type? What is wrong actually?