我有一个看起来像这样的类型
export type Theme = | 'primary'
| 'secondary'
| 'success'
| 'danger'
| 'warning'
| 'info'
| 'dark'
| 'light'
现在,我正在创建一个映射,我希望键与主题中的键相同,所以我尝试了这个,但这一直抛出以下错误
const colorMapping: { [key: Theme]: string } = {
primary: '#0275d8',
success: '#5cb85c'
}
An index signature parameter type cannot be a union type. Consider using a mapped object type instead
有人可以帮我解决这个错误吗?
最佳答案
根据错误消息的建议,使用 mapped type :
export type Theme = 'primary'
| 'secondary'
| 'success'
| 'danger'
| 'warning'
| 'info'
| 'dark'
| 'light';
const colorMapping: { [key in Theme]?: string } = {
primary: '#0275d8',
success: '#5cb85c'
};
关于typescript - 添加类型作为对象的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63554406/