【发布时间】:2021-12-21 21:37:30
【问题描述】:
我正在尝试使用带有条件语句的接口。
在一个界面中,我知道我们可以在下面有这样的东西来设置条件。
interface exampleInterface {
a: 'A' | 'B'
}
这样,我们可以确保输入“a”必须是“A”或“B”。 我想从 ['A', 'B'] 之类的数组中填充这种条件
下面有什么方法可以做到吗?
const a_list = Object.keys(config.a_list) // ['A', 'B'] I want to generate this from the config file.
interface exampleInterface {
a: oneOf(a_list)
}
我想这样的原因是输入数组是动态的(从配置文件中获取信息)。 任何想法或建议都会有所帮助。谢谢。
其他信息: 我已经从配置文件创建了数组,并在界面中执行了以下操作。
interface myInterface {
a: typeof a_list[number],
}
但是当我尝试从如下用户输入的配置文件中获取信息时,我收到以下错误。
export default function myFunc(props: myInterface)
const [a] = useState(config.a_config[props.a].map((a) => a))
// Element implicitly has an 'any' type because the expression of type 'string' can't be used to index type.
// No index signature with a parameter of type 'string' was found on the type.
【问题讨论】:
-
你用过
enum吗?您可以定义它,然后在道具中使用类似的类型 -
不是来自配置。只有
const a_list = ['A', 'B'] as const,然后是a: typeof a_list[number]
标签: reactjs typescript dynamic interface