Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript loop trough Object

Tags:

typescript

I have this really easy problem, where I want to loop through an Object in TypeScript.

const an_object = {
    one: 1,
    two: 2,
    three: 3
};

for (let key in an_object) {
    let value = an_object[key];
    // Do something with value
}

This row let value = an_object[key]; is causing a TypeScript error:

[react-scripts] Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{ one: number; two: number; three: number; }'.

I'm new to TypeScript and don't really understand the problem.

This works fine on JavaScript but not on TypeScript.

Any suggestions on how to loop through an object in TypeScript correctly, without getting errors?

like image 265
OuuGiii Avatar asked Jun 16 '26 03:06

OuuGiii


2 Answers

TypeScript is named TYPEScript for a reason.

The problem is that it's not specified what will be inside the object.

Any suggestions on how to loop through an object in TypeScript correctly, without getting errors?

To do this correctly you should specify what is inside the object. This can be done by:

  1. creating an interface
interface MyObjectsInterface {
    [key: string]: number;
}
  1. assign it to the object.
const an_object: MyObjectsInterface = {
    one: 1,
    two: 2,
    three: 3
};
  1. now you can use the value in the forloop
for (let key in an_object) {
    let value: number = an_object[key];
    // Do something with value
}

In this way, you will always know what will be inside an object.

like image 160
OuuGiii Avatar answered Jun 18 '26 17:06

OuuGiii


For this purpose, I usually write a helper function, so that my "for each object property" loops can be written like follows:

objForEach(an_object, (k, v) => {
    console.log('key', k, 'value', v);
});

The implementation is below. Helpfully, by making it generic, the parameters k and v can have their types inferred correctly depending on an_object:

function objForEach<T>(obj: T, f: (k: keyof T, v: T[keyof T]) => void): void {
    for (let k in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, k)) {
            f(k, obj[k]);
        }
    }
}

Note that I've used hasOwnProperty to check that the property belongs to the object itself rather than another object in its prototype chain (see e.g. this question).

like image 40
kaya3 Avatar answered Jun 18 '26 16:06

kaya3