eAbi
eAbi

Reputation: 3470

Typescript object iteration compiler problems

Given the following code in a file named test.ts:

interface ImageFile {
    width: number;
    height: number;
    url: string;
}

interface ImageFiles {
    low: ImageFile;
    medium?: ImageFile;
    high?: ImageFile;
}

let images: ImageFiles = {
    low: {
        width: 0,
        height: 0,
        url: 'bla'
    }
};

Object.keys(images).forEach((k) => {
    let img = images[k];
    // do something with img
});

Gives the following error when compiling with --noImplicitAny option:

$ tsc test.ts --noImplicitAny
test.ts(22,10): error TS7017: Index signature of object type implicitly has an 'any' type.

Meaning that images[k] type implicitly has an anytype, and also, type casting won't work here.

Compiling without --noImplicitAny flag works ok.

How can I correctly iterate through an object when the above flag is set?

Upvotes: 3

Views: 183

Answers (1)

Seamus
Seamus

Reputation: 4829

The TypeScript compiler cannot infer the correct type for images[k], and that's why it is complaining. As you've discovered, type casting does not fix the problem.

Instead, you can use an index signature to tell the compiler that all properties of an ImageFiles object are of type ImageFile:

interface ImageFiles {
    [key: string]: ImageFile;
    low: ImageFile;
    medium?: ImageFile;
    high?: ImageFile;
}

Upvotes: 3

Related Questions