预先未知属性名称的打字稿类

时间:2021-01-02 23:17:21

标签: typescript

这是我试过的

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'

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

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

有没有办法解决这个问题?

3 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:2)

实际上可以通过declaration merging来实现。 只需将接口命名为与类相同的名称即可。

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

interface SomeClass { 
  [key: string]: SpecificType
}
 
class SomeClass {
  field1 = {
   a: 1,
   b: ""  
 }
}

如果你有多个类,那么像这样使用它:

type SpecificType = {a:number; b:string};
type SomeInterface = {
  [key: string]: SpecificType
};

interface SomeClass extends SomeInterface { }
class SomeClass {
  field1 = {
   a: 1,
   b: ""  
 }
}

TS Playground

答案 2 :(得分:1)

您可以使用泛型类型来做您想做的事情:但是,这是在实现 SomeInterface 时您已经知道类的哪些成员应该实现该接口的条件。否则,这就是鸡与蛋的问题,而您原来的方法将是唯一的解决方案。

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

type SomeInterface<T extends string> = { 
  [key in T]: SpecificType
}

class SomeClass implements SomeInterface<'field1'> {
  field1 = {
    a: 1,
    b: ""
 }
}

TypeScript playground 上查看。