1

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.)

4
  • can't use let key:any in props? Commented Jun 28, 2021 at 18:10
  • 1
    No, because "the left-hand side of a for...in statement cannot use a type annotation" Commented Jun 28, 2021 at 18:32
  • 2
    Common pattern to iterate with for ... in is: let key: keyof (typeof obj); for (key in obj) ... Commented Jun 28, 2021 at 19:58
  • @aleksxor Thanks, that did the trick! Commented Jun 29, 2021 at 13:21

3 Answers 3

3

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)) {
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0
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.

Comments

0

In this case you can use keyof (object operator) to explicitly tell interpreter. For example:

function myFunc(props: LabeledProps):void {
    for (let key in props) {
        const val = props[key as keyof LabeledProps]; 
        // do other stuff
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.