icfantv
icfantv

Reputation: 4643

Typescript compiler not erroring on const with explicit type

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?

Upvotes: 0

Views: 144

Answers (1)

Ryan Cavanaugh
Ryan Cavanaugh

Reputation: 221044

TypeScript gave the variable BAR the type "bar" because that was its initializer. This means that bar[BAR].foo is number because bar.bar.foo is number and those things mean the same thing.

With BAR2, you explicitly overrode the inference so it has the type string instead of the type "bar". When you index an object by a string, you get an implicit any.

Upvotes: 4

Related Questions