TypeScript接口可以限制其实现类的属性吗?

问题描述 投票:1回答:1

我想定义一个类,该类可以具有任何string属性键,但是具有特定的对应值类型。我尝试了以下方法:

interface MyValue {
  body: string;
  description: string;
}

interface MyInterface {
  [key: string]: MyValue;
}

class MyClass implements MyInterface {}

我希望以上内容将导致在以下情况下有效的MyClass

class MyClass implements MyInterface {
  a = {
    body: "lorem ipsum";
    description: "some latin placeholder",
  };
}

...以下内容无效:

class MyClass implements MyInterface {
  a = "lorem ipsum";
}

相反,我得到一个错误:

Class 'MyClass' incorrectly implements interface 'MyInterface'.
  Index signature is missing in type 'MyClass'.

是否有使用类的方法,并且仍然可以实现上述所需的行为?

谢谢!

typescript class interface signature implements
1个回答
0
投票

您不能使用索引签名来执行此操作。如果您的接口具有索引标记,则您的课程也将需要一个。

您可以使用映射类型将类的所有键(属性和方法)限制为特定类型:

type MyInterface<K extends PropertyKey> = {
  [P in K] : MyValue
}

class MyClassEmpty implements MyInterface<keyof MyClassEmpty> {}

class MyClassGood implements MyInterface<keyof MyClassGood> {
  a = {
    body: "lorem ipsum",
    description: "some latin placeholder",
  };
}

class MyClassBad implements MyInterface<keyof MyClassBad> {
  a = "lorem ipsum"; // error
}

Playground Link

© www.soinside.com 2019 - 2024. All rights reserved.