首页 > 解决方案 > 预先不知道属性名称的打字稿类

问题描述

这是我尝试过的

type SpecificType ={a:number; b:string};

type SomeInterface { 
  [key: string]: SpecificType
}  
class SomeClass implements SomeInterface {
  field1: {
   a: 1,
   b: ""  
 }
}

问题是我收到此错误:Index signature is missing in type 'SomeClass'

如果我放入 SomeClass,它就会消失[key:string]: SpecificType,但我想避免这种情况。

此外,TS 无法识别 SomeClass 中的字段类型。

有解决方案吗?

标签: typescript

解决方案


type SpecificType = { a: number; b: string };

abstract class SomeAbstractClass {
  [key: string]: SpecificType;

}
class SomeClass extends SomeAbstractClass {
  fields1 = {
    a: 1,
    b: "2"
  }
}

推荐阅读