【发布时间】:2020-05-31 00:19:13
【问题描述】:
我希望dropdownAttributes 仅限于DropDownItem 接口上的属性。
interface DropDownItem {
[key: string]: any;
}
interface Props {
dropdownList: DropDownItem[];
dropdownAttributes: string[];
}
如果DropDownItem 现在确实有动态属性,我想我可以像这样用keyof 解决这个问题:
interface Props {
dropdownList: DropDownItem[];
dropdownAttributes: (keyof DropDownItem)[];
}
但这在我的情况下现在不起作用。如何解决?
【问题讨论】:
-
我认为你不能再锁定它了。
DropDownItem允许任何字符串键保存任何值,因此在dropdownAttributes中包含字符串是尽可能紧凑的。正如你所说,如果DropDownItem没有索引签名,你可以进一步限制dropdownAttributes,但就这样,你不能。 (在 TypeScript 级别。) -
但是
DropDownItem有一个索引签名,所以它可以有任何键,所以keyof DropDownItem只是string(好吧string | number但那是另一回事)。如果密钥未知,TS 无法帮助您在编译时强制执行它们。
标签: typescript keyof