Ansh Gujral
Ansh Gujral

Reputation: 291

How to provide types in the for.. in.. loop in typescript?

I want to provide type to the constant property

var object = {...Sample object};

for (const property in object) {
    console.log(property);
}

Is it possible?

Upvotes: 0

Views: 251

Answers (1)

Lesiak
Lesiak

Reputation: 25936

As for..in statement documentation states:

The for...in statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols), including inherited enumerable properties.

const object = {a: 1, b: 2, c: 3};

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

// expected output:
// "a: 1"
// "b: 2"
// "c: 3"

Your property variable is inferred by TypeScript compiler to be a string. There is no need for type hints from the programmer.

Upvotes: 3

Related Questions