Tom Esterez
Tom Esterez

Reputation: 22137

Typescript: Prevent unexpected usage of object[index]

I was surprised to notice that typescript is ok with the following code:

interface IFoo {
  bar: string;
}

const foo: IFoo = {bar: 'bar'};

console.log(
  foo['anything'] // I'd like typescript to prevent this
);

Is there a way to prevent usage of [] accessor when not expected?

Upvotes: 2

Views: 52

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 240948

Is there a way to prevent usage of [] accessor when not expected?

If you want an error to be thrown you could enable the noImplicitAny flag, which would result in the following error:

Element implicitly has an any type because type IFoo has no index signature.

Upvotes: 3

Related Questions