[英]Typescript define type for object will loose static object key (property) suggestion
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.
不期望:截图
预期:屏幕截图 - 预期
建议或 static 类型检查定义类型的任何属性也手动添加键。
喜欢:
interface ButtonProps {
primary: ...,
[key: string]: ...
}
const button: ButtonProps = {
secondary: ...
}
button.primary // ✅
button.secondary // ✅
button.third // Okay, but no suggestion.
实际上,我最近自己也遇到了类似的情况。 问题是您希望获得您定义的 object 的窄类型,同时确保它扩展更广泛的类型。 要解决此问题,您可以创建一个 function,它只返回其输入但推断其类型。
interface ButtonProps {
primary: {background:string, color:string};
[key: string]: any;
}
const createButtonProps = <T extends ButtonProps>(props: T) => props;
export const button = createButtonProps({
primary: { // primary is required
background: theme.background.primary,
color: theme.color.base,
},
base: {
background: theme.background.base,
color: theme.color.primary,
},
});
// You'll now see intellisense for button.primary & button.base
作为奖励,如果您也需要在 object 中获取确切的值类型,我就是这种情况,您可以将as const
添加到您传递给 ZC1C425268E68385D14AB5074C17A 的 object 的末尾。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.