typescript - 添加类型作为对象的键

标签 typescript

我有一个看起来像这样的类型

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/

相关文章:

javascript - Angular 2 - 比较数组过滤器中的日期

Angular 2 Observable.forkJoin 与 for 循环

typescript - 当没有要指定的确切值 'undefined' 或 'null' 时,为 TypeScript 可选参数传递什么?

typescript - 为什么 TypeScript 不推断某些管道函数的类型?

node.js - 如何修复找不到模块 'fs'

javascript - 执行 bundle 时使用各自子包的模块

typescript - 带有 readline(询问者)问题的异步/等待循环

javascript - Typescript 'keyof InstanceType<T>' cannot be used to index type 错误

javascript - 具有单个或多个数据源的两个垫分页器无法正常工作

windows - 如何使用 Visual Studio 2010 安装 TypeScript