N
N
Ne7Le4Der2021-10-27 11:19:47
typescript
Ne7Le4Der, 2021-10-27 11:19:47

How to correctly initialize an object with a different set of fields in Typescript?

The following object comes from the API:

{
   key1: "value1",
   key2: "value2"
}


There are a different number of keys and a different name (i.e. this time key1, key2 came. And the next request may come key145, key555)

Can this be done somehow other than :any?
let object: any;

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-27
@Ne7Le4Der

Record<string, string>
If the keys suddenly and in truth always start with key, then you can do this: Record<`key${number}`, string>.:)
If you want TS to always force you to check that the value is there, then like this:
Record<string, string|undefined>

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question