javascript - Typescript 为对象定义类型将丢失静态对象键(属性)建议
问题描述
这是代码:
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.
不期望: 截图
预期: 屏幕截图 - 预期
预期行为:
对定义类型的任何属性的建议或静态类型检查也手动添加了键。
像:
interface ButtonProps {
primary: ...,
[key: string]: ...
}
const button: ButtonProps = {
secondary: ...
}
button.primary // ✅
button.secondary // ✅
button.third // Okay, but no suggestion.
解决方案
实际上,我最近自己也遇到了类似的情况。问题是您希望获得您定义的对象的窄类型,同时确保它扩展更广泛的类型。要解决此问题,您可以创建一个仅返回其输入但推断其类型的函数。
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
作为奖励,如果您还需要获取对象中的确切值类型(对我来说就是这种情况),您可以添加as const
到传递给函数的对象的末尾。
推荐阅读
- ruby - 我刚刚回到过去
- node.js - 无法使用反应功能调用 express app.post
- python-2.7 - 如何使用 Robotframework 自动化 iframe 中的文本字段
- reactjs - 子组件看不到父组件状态更新
- windows - 将 __int64 转换为 FileTime
- java - 如何限制用户在数据库中多次写入
- javascript - 更改标记中包含的某些值的字体颜色
- mysql - MySQL 2 个日期之间的时间(分钟)差
- php - 图像在imagick中变暗
- javascript - 使用输入值创建一个对象并将其添加到现有数组 JavaScript