gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:37:57 25 4
gpt4 key购买 nike

我正在尝试定义一种类型,其中 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

最佳答案

我发现了这个:How to convert array of strings to typescript types? .

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

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

关于javascript - TypeScript:使用扩展运算符指定值必须在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70999268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com