1

I want to make a list or array from all possible variants of a custom type.

Ex. The custom type:

export type FruitType= 'Apple' | 'Orange' | 'Strawberry' | 'Banana'; 

Wanted result:

const FruitArray = ['Apple', 'Orange', 'Strawberry', 'Banana']

Is this achievable or is hardcoding the list the only way?

I'm working in React with typescript

2 Answers 2

4

As TypeScript is just transpiled to JavaScript, the type information is only available at compile time, not at run time. You will have to re-define the value somewhere they're available at run time.

What you can do is define the array and then define a type based on it:

const fruitArray = ['Apple', 'Orange', 'Strawberry', 'Banana'] as const;
type FruitType = typeof fruitArray[number];
const fruit: FruitType = 'Apple';

However, FruitType will only allow values that are actually hard-coded into fruitArray from the very beginning.

Sign up to request clarification or add additional context in comments.

Comments

1

If you can use enum instead type then you can write the next code:

enum FruitType {
  Apple = 'Apple',
  Orange = 'Orange',
  Strawberry = 'Strawberry',
  Banana = 'Banana',
}

const array = Object.values(FruitType);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.