M -
M -

Reputation: 28482

Typescript - bracket index into object does not yield error

I'm finding that TypeScript is letting me use bracket notation to access an object via index, when it only has keys. For instance:

interface testObject {
    name: string;
    id: number;
}

let first: testObject = {name: "Marquizzo", id: 1};

let second = first[1]; // <-- Should yield error!

first[1] should give me an error because 1 is not defined as a valid key in the testObject interface. Is there a flag that I can turn on to avoid this from happening?

Upvotes: 3

Views: 242

Answers (1)

cartant
cartant

Reputation: 58400

It sounds like you do not have the noImplicitAny compiler option set to true.

With that option set to false no error is effected, but if it's set to true an error is effected:

[ts] Element implicitly has an 'any' type because type 'testObject' has no index signature.

Upvotes: 3

Related Questions