【发布时间】:2021-04-14 07:08:17
【问题描述】:
代码如下:
interface ButtonProps {
[key: string]: any
}
export const button: ButtonProps = {
primary: {
background: theme.background.primary,
color: theme.color.base,
},
base: {
background: theme.background.base,
color: theme.color.primary,
},
}
// button.pr..
// ???? When I press primary, the vscode static suggestion won't show `primary` or `base` keys, because [key: string] could be any string.
不期望: Screenshot
预期行为:
对定义类型的任何属性的建议或静态类型检查也手动添加键。
喜欢:
interface ButtonProps {
primary: ...,
[key: string]: ...
}
const button: ButtonProps = {
secondary: ...
}
button.primary // ✅
button.secondary // ✅
button.third // Okay, but no suggestion.
【问题讨论】:
-
没有建议因为
[key: string] -
ButtonProps被定义为{ [key: string]: any },这意味着键可以是任何字符串,所以你不能指望静态编译器给你一些建议。我建议你最好用更严格的类型来设计ButtonProps,实际的类型是没用的。 -
那我怎样才能两者兼得?
标签: javascript reactjs typescript frontend