Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript object iteration compiler problems

Tags:

typescript

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?

like image 520
eAbi Avatar asked May 07 '26 02:05

eAbi


1 Answers

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;
}
like image 197
Seamus Avatar answered May 11 '26 17:05

Seamus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!