问题描述
我有一个名为IRawParams
的接口类型,该接口类型仅指定了string
键和any
值.
I have an interface type called IRawParams
which simply specifies a string
key and any
vals.
interface IRawParams {
[key: string]: any
}
我有一个类,ParamValues
,其中包含一些在键/值之上的行为.我想指定ParamValues
类实现IRawParams
接口.
I have a class, ParamValues
which contains some behavior on top of keys/values. I'd like to specify that the ParamValues
class implements IRawParams
interface.
class ParamValues implements IRawParams {
parseFromUrl(urlString: string) {
Parser.parse(urlString).forEach(item => this[item.key] = item.val);
}
}
// so I can do something like this
var params = new ParamValues();
params.parseFromUrl(url);
var userId = params.userId;
尝试此操作时,出现编译器错误:
When I attempt this, I get a compiler error:
我可以让我的类实现IRawParams接口,还是让Typescript允许我的类的实例与索引类型{[key: string]: any}
兼容?
Can I get my class to implement the IRawParams Interface, or otherwise get Typescript to allow instances of my class to be compatible with an indexed type {[key: string]: any}
?
推荐答案
要定义具有索引签名的类,只需在该类中编写索引签名:
To define a class with an index signature, just write the index signature in the class:
interface IRawParams {
[key: string]: any
}
class Foo implements IRawParams {
[k: string]: any;
}
这篇关于我可以定义具有索引签名的Typescript类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!