我正在尝试定义一个类型,其中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
我希望这就是您想要的
[更新]
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)
你可以保持你的选项列表动态
你可以在这里测试
我发现:如何将字符串数组转换为typescript类型。
const arr = ["foo", "bar", "loo"] as const
type arrTyp = typeof arr[number]; // "foo" | "bar" | "loo"