4

I am trying to define a type where the favoriteFruit property's value must be an item in options array. Where the options array is dynamic/unknown (making it impossible to use union types "|").

const options = ["apple", "orange", "kiwi"]; // Dynamic list that can be modified in the future 

type Person =  {
  name: string;
  favoriteFruit: /* --- val in [...options] --- */
};

const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK
const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK
const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROR

2 Answers 2

2

I hope this is what you are looking for

[UPDATED]

const options = ["apple", "orange", "kiwi"] as const; // Dynamic list that can be modified in the future 
type optionsType = typeof options[number];

type Person =  {
  name: string;
  favoriteFruit: optionsType;/* --- val in [...options] --- */
};

const personA:Person = {name: "Jack", favoriteFruit: "apple"}; // OK
const personB:Person = {name: "John", favoriteFruit: "orange"}; // OK
const personC:Person = {name: "Jane", favoriteFruit: "banana"}; // ERROR
console.log(personC)

you can keep your options list dynamic

You can test here

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

Comments

2

I found this : How to convert array of strings to typescript types? .

const arr = ["foo", "bar", "loo"] as const

type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"

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.