[英]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.我正在尝试定义一种类型,其中 favoriteFruit 属性的值必须是选项数组中的一个项目。 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?我发现了这个: 如何将字符串数组转换为 typescript 类型? .
.
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你可以保持你的选项列表动态
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.