【问题标题】:Typescript: enum index from database gives type error打字稿:数据库中的枚举索引给出类型错误
【发布时间】:2021-10-03 02:26:36
【问题描述】:

在我的 Discord 机器人中,我有一个带有审核图标的枚举:

export enum moderationIcon {
    ban = '????',
    kick = '????',
    pardon = '????',
    warn = '????'
}

当我创建审核历史时,我想添加这样的图标:moderationIcon[moderationRow.type.toLowerCase()],但我遇到了这个错误:

元素隐式具有“any”类型,因为“string”类型的表达式不能用于索引“typeof moderationIcon”类型。 在“typeof moderationIcon”类型上找不到带有“string”类型参数的索引签名。

如何解决这种错误?

moderationRow.type 是 'BAN'、'KICK'、PARDON' 或 'WARN')

【问题讨论】:

  • 试试moderationIcon[moderationRow.type.toLowerCase() as keyof typeof moderationIcon]
  • 把枚举键大写怎么样?一个需要大写另一个小写有什么原因吗?

标签: typescript types


【解决方案1】:

toLowerCase() 的返回类型为string,比'typeof moderationIcon' 更通用。

我认为您目前可以实现的最接近和最安全的事情是使用在 typescript 4.1 中添加的Template Literal Types 编写一个 getter 函数。但它涉及演员:

function getModerationIcon(type: Uppercase<keyof typeof moderationIcon>) {
  return moderationIcon[type.toLowerCase() as keyof typeof moderationIcon]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-02
    • 2017-03-09
    • 2021-11-10
    • 2019-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多