繁体   English   中英

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

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

我正在尝试定义一种类型,其中 favoriteFruit 属性的值必须是选项数组中的一个项目。 选项数组是动态/未知的(无法使用联合类型“|”)。

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

我发现了这个: 如何将字符串数组转换为 typescript 类型? .

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)

你可以保持你的选项列表动态

你可以在这里测试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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