TypeScript:使用扩展运算符指定值必须在数组中

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

我正在尝试定义一种类型,其中 favoriteFruit 属性 的值必须是选项数组中的一项。其中选项数组是 dynamic/unknown(因此无法使用联合类型“|”)。

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

我发现了这个: .

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

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

希望这就是您要找的

[更新]

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 test here