简体   繁体   中英

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

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM