Typescript index error: looping through keys of typed object

Viewed 228

I have an interface that's created as an extension of a couple of other interfaces from an external library:

interface LabeledProps extends TextProps, ComponentProps {
    id: string;
    count: number;
    ...
}

In another place in the code, I have an object of type LabeledProps and I would like to loop through all its properties:

function myFunc(props: LabeledProps):void {
    for (let key in props) {
        const val = props[key];  // <-- ERROR IS HERE
        // do other stuff
    }
}

The line const val = props[key] throws a typescript error (though the compiled code actually runs just fine):

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'LabeledProps'.

What is the right way (or ways) to accomplish this? Thanks!

(Note: I know I could add [key: string]: any to the interface definition and that will remove the error message, but I would like an actual fix, not just a hiding-the-error fix.)

2 Answers

In this case, you want to iterate over object pairwise. There is a useful utility, called Object.entries, which removes the error.

type LabeledProps = {
    name: string,
    age: number
}

const obj: LabeledProps = {
    name: 'Maks', age: 18
}

for (let [ key, value ] of Object.entries(obj)) {
    ...
}
function myFunc(props: LabeledProps):void {
    Object.values(props).forEach(val => {
        // do other stuff
    });
}

I agree with the other answers here and the comments. The responses of others were all great, and this is only offered as yet another way to do it.

Related