C
C
camradee2022-01-12 13:33:55
typescript
camradee, 2022-01-12 13:33:55

What does the definition below mean in Typescript?

I study TS and it seems to be clear in pieces, but all together there is no whole picture. What does this entry do?

const someVariable: string[] | Record<string, any>[] = [
      "id",
      "name",
      "description",
      {
        "fullPrice": "price"
      },
      {
        "qty": "quantity"
      }
    ]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2022-01-12
@bingo347

The Record type is a utility type from the TS standard library that describes an object whose keys are the first generic argument and the values ​​are the second.
A type string[] | Record<string, any>[]is either an array of strings or an array of objects (the key is any string, the value is any type). This type will not allow you to mix strings and objects in the same array, either one or the other.
As WbICHA rightly pointed out in a comment to the question, the correct type for the given data is (string | Record<string, any>)[](an array of strings or objects mixed up).
Well, instead of any, it’s better to use unknown, any is a type without type checking, unknown is a type that includes all other types, you can also write a value of any type to it, like any, but unlike any, when using unknown, you need do either explicit type casting or type checking runtime.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question