【问题标题】:Add type annotation for property value shorthand为属性值简写添加类型注释
【发布时间】:2022-10-13 20:43:46
【问题描述】:

MergedObject 可以保存任意数量的MyClass 实例变量名到MyClass 实例键值对,其中属性名是变量名,例如Obj1,值是MyClass 实例。如何为MergedObject 添加类型注释?

class MyClass {
  a: string;
  constructor(a: string) {
    this.a = a
  }
}

const Obj1 = new MyClass('one')
const Obj2 = new MyClass('two')

const MergedObject = {
  Obj1, Obj2
}
``

【问题讨论】:

    标签: typescript typescript-typings typescript-generics


    【解决方案1】:

    一种可能的类型注释是具有包含MyClass 值的字符串索引签名的对象。

    const MergedObject: Record<string, MyClass> = {
      Obj1, Obj2
    }
    

    Playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      • 2019-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      相关资源
      最近更新 更多