【发布时间】:2020-06-26 23:22:48
【问题描述】:
我想定义一个类,它可以有任何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