我可以定义一个具有索引签名的 Typescript 类吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31977481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I define a Typescript class which has an index signature?
提问by Chris T
I have an interface type called IRawParams
which simply specifies a string
key and any
vals.
我有一个名为的接口类型IRawParams
,它只是指定一个string
键和值any
。
interface IRawParams {
[key: string]: any
}
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.
我有一个类,ParamValues
其中包含键/值之上的一些行为。我想指定ParamValues
该类实现IRawParams
接口。
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:
当我尝试这样做时,我收到一个编译器错误:
error TS2420: Class 'ParamValues' incorrectly implements interface 'IRawParams'. Index signature is missing in type 'ParamValues'.
错误 TS2420:“ParamValues”类错误地实现了“IRawParams”接口。“ParamValues”类型中缺少索引签名。
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}
?
我可以让我的类实现 IRawParams 接口,或者以其他方式获取 Typescript 以允许我的类的实例与索引类型兼容{[key: string]: any}
吗?
回答by Ryan Cavanaugh
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;
}