1

I am new to using React with typescript and I recently came across the following issue. It is my understanding that if I am declaring my initial state as an empty array like so:

const [todos, setTodos] = useState<{ id: string; text: string }[]>([])

I need to provide typescript with an interface of what the array will eventually look like. hence the useState<{ id: string; text: string }[]>. What I am curious about is the use case of me fetching data from an api, etc. and the schema is very large or the values are dynamic. How do I go about letting typescript know what my empty array will eventually be set to. If i'm fetching an extremely large array of objects, I feel as though it wouldn't be efficient to have to go through and outline each key-value pair. Or if the data is dynamic how could I possibly outline the schema?

Rob Terrell
  • 2,398
  • 1
  • 14
  • 36
  • what if i don't know the overall shape because it's dynamic is what im asking – Rob Terrell Jun 13 '21 at 20:53
  • 1
    If the data is dynamic then you can use something like `any[]` or `Record[]` or you could just define a simplified type or interface that has only the properties you know are always there and you actually use. – apokryfos Jun 13 '21 at 20:54

1 Answers1

-1

You can use a `Record<string,unknown> type for each array element

const [todos, setTodos] = useState<Array<Record<string, unknown>>>([])
Kwame Opare Asiedu
  • 2,110
  • 11
  • 13
  • 1
    Using Any is not a good idea. As @apokryfos said,. We can use Record type for the unknown keys and values. – aditya81070 Jun 14 '21 at 01:24
  • If that's the case, wouldn't `Record` also not be a good idea since the value type is `any`? Also @apokryfos suggested `any[]` ... – Kwame Opare Asiedu Jun 14 '21 at 08:57
  • Yes, it is not good. The ideal type should be `Record` as we don't what will be the type of data from the API. so if we use `unknown` instead of `any` then TS will give us an error before consuming any of these values. For example if response is `[{key: 'string'}]` and type is `any` then we can directly use `state[0].key.toUpperCase()` but if it was unknown, we have to check the type first. That is the safety unknown provides over any. – aditya81070 Jun 14 '21 at 09:45
  • Check this answer for more details: https://stackoverflow.com/a/51439876/7852473 – aditya81070 Jun 14 '21 at 09:46
  • I see. Thanks for the link. It seems I still have much to learn about Typescript... – Kwame Opare Asiedu Jun 14 '21 at 09:57
  • Yeah, that's okay. Can you please update your answer so it can help future readers? – aditya81070 Jun 14 '21 at 09:59