J
J
jeruthadam2020-05-20 01:09:04
typescript
jeruthadam, 2020-05-20 01:09:04

Why is Typescript showing an error?

I started to study the TS, and I can not understand why it shows an error here?

const data: {
  hello: {
    wtf: string
  }
} = {
  hello: {
    wtf: 'world'
  }
}

for (const [key] of Object.entries(data)) {
  console.log(data[key]); // ошибка тут data[key]
}


How to access object property without error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
ned4ded, 2020-05-20
@jeruthadam

Typescript shows an error because it types any object keys passed to Object.keys and Object.entries as strings (not string constants). This is inherent behavior. The reason the developers say is: "an object can have more properties at runtime, so the type is string[]" ( thread1 , thread2 ).
Access to the property of the object without an error in this case can be obtained only if you set the typing yourself.
The simplest solution:

const data: {
    hello: {
        wtf: string;
    };
} = {
    hello: {
        wtf: 'world',
    },
};

for (const [key] of Object.entries(data) as [keyof typeof data, any][]) {
    console.log(data[key]); 
}

The readability of such code, of course, suffers greatly. More suitable option:
interface Data {
    hello: {
        wtf: string;
    };
}

type DataKey = keyof Data;

const data: Data = {
    hello: {
        wtf: 'world',
    },
};

for (const [key] of Object.entries(data) as [DataKey, any][]) {
    console.log(data[key]);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question