TypeScript: Specify that value must be in Array using spread operator

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error TypeScript: Specify that value must be in Array using spread operator on this date .

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

Answer

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