-1

I have the array:

const studyTypes = [
   {
     value: "ENG",
     label: "ENG-RU",
   },
   {
     value: "RU",
     label: "RU-ENG",
   },
];

And the state:

const [typeStudy, setTypeStudy] = React.useState<string>("ENG");

How can I specify in typescript that my typeStudy can only take one of the value from the studyTypes array instead of a <string>? In this case the typeStudy can be either "ENG" or "RU".

kan
  • 43
  • 5
  • Does this answer your question? [TypeScript array to string literal type](https://stackoverflow.com/questions/44497388/typescript-array-to-string-literal-type) – Tawfik Nasser Nov 30 '21 at 20:45

2 Answers2

1

If you could declare studyTypes as a const, it should be like this:

const studyTypes = [
   {
     value: "ENG",
     label: "ENG-RU",
   },
   {
     value: "RU",
     label: "RU-ENG",
   },
] as const; // as const is important for this step

type Value = typeof studyTypes[number]['value'];


const testValue: Value = "PQR" // This will throw a type error.

This will only work with Typescript v3.4 or greater.

Here's an example from my VSCode checking for lint errors: dynamic types

Harkunwar
  • 653
  • 5
  • 10
-1

You can define a new type as literal type.

type TypeStudy = "ENG" | "RU";

and then

React.useState<TypeStudy>
Tawfik Nasser
  • 1,018
  • 9
  • 17