typescript - 如何使用对象条目作为打字稿中嵌套对象的索引?
问题描述
我正在尝试使用对象条目作为嵌套对象的索引,如下所示:
type Size = 'small' | 'medium' | 'large';
type Variant = 'primary' | 'secondary';
const styles: {
size: Record<Size, object>;
variant: Record<Variant, object>;
} = {
size: {
small: { padding: 8 },
medium: { padding: 12 },
large: { padding: 16 },
},
variant: {
primary: { background: 'hotpink' },
secondary: { background: 'silver' },
},
};
const props: { size: Size; variant: Variant } = {
size: 'medium',
variant: 'primary',
};
const css = (Object.keys(props) as Array<keyof typeof props>).reduce(
(acc, key) => {
const value = props[key];
return { ...acc, ...styles[key][value] };
// ^ Element implicitly has an 'any' type because
// expression of type '"small" | "medium" | "large" | "primary" | "secondary"'
// can't be used to index type 'Record<Size, object> | Record<Variant, object>'
},
{}
);
我as Array<keyof typeof ...>
用来避免Object.keys
只提供string[]
密钥——但我不确定如何处理生成的联合类型?
解决方案
推荐阅读
- json - getent passwd 以正确格式输出为 json
- c# - C# 在两个控制器 ActionResults 之间失去价值
- visual-studio-mac - 你如何在 Visual Studio 2017 社区中查看 MAC 的完整错误
- javascript - 我可以让它只在某个变量为真时才执行点击事件吗?
- python - Python使用空格sep从csv读取数据,第一列除外
- azure-machine-learning-workbench - 在本地运行 Azure 机器学习服务管道
- macos - 如何从命令行在 Mac 上运行 MSTest 单元测试?
- javascript - 如何将多个类属性设置为一个对象的属性
- r - (R) 将文本添加到字符串值的 for 循环不起作用
- foreign-keys - 用于在线学生监控系统的 Mysql 数据库设计的数据库错误