【问题标题】:A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type类型文字中的计算属性名称必须引用其类型为文字类型或“唯一符号”类型的表达式
【发布时间】:2021-08-20 04:24:12
【问题描述】:

最终我想计算如下内容

const configOne = {
  default: {master: 0},
  sg: {master: 1},
}

const configTwo = {
  default: {master: 1}
}

基本上object 必须有default 作为强制属性,然后其余属性可以是可选的,但它们必须是国家前缀。以下是我的尝试

enum CID {
  'tw',
  'sg',
  'vn',
}

interface IIndividualConfig {
  master: 0 | 1;
}

type IConfig = {
  default: IIndividualConfig;
  [key in CID]?: IIndividualConfig;
}


const configOne: IConfig = {
  default: { master: 0 },
  sg: {master: 1}
}


const configTwo: IConfig = {
  default: { master: 1 }
}

下面是我在[key in CID]遇到的错误

A computed property name in a type literal must refer to an expression whose type is a literal type or a 'unique symbol' type.ts(1170)
A computed property name must be of type 'string', 'number', 'symbol', or 'any'.ts(2464)

【问题讨论】:

    标签: javascript typescript interface partial


    【解决方案1】:

    出现问题是因为您在使用index signature 时在定义中定义了default,如下所示

    type IConfig = {
      default: IIndividualConfig; // <= Causing error
      [key in CID]?: IIndividualConfig;
    }
    

    可能的解决方法 1:

    type IConfig = {
      [key in CID | 'default']?: IIndividualConfig;
    }
    

    这不会给您错误,但可能不是 100% 适合用例,因为 default 不再是强制性的。因此可能需要查看选项 2

    解决方法 2:

    type IDefaultConfig = { default: IIndividualConfig; }
    type IConfig = IDefaultConfig & {[key in CID]?: IIndividualConfig; };
    

    现在通过使用intersection,我们将两种类型合并为一个类型,default 将是必需的,其他键是可选的,如果定义它们必须是CID 类型

    【讨论】:

      猜你喜欢
      • 2017-10-21
      • 2021-08-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-07
      相关资源
      最近更新 更多