Tom Esterez Tom Esterez - 4 years ago 191
TypeScript Question

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download