Kingsley CA
Kingsley CA

Reputation: 11624

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

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

Upvotes: 4

Views: 1443

Answers (2)

Irfan Anwar
Irfan Anwar

Reputation: 1918

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

Upvotes: 2

Martin Nenov
Martin Nenov

Reputation: 21

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"

Upvotes: 2

Related Questions