Can I define a Typescript class which has an index signature?

烈酒焚心 提交于 2020-03-18 10:25:02

问题


I have an interface type called IRawParams which simply specifies a string key and any vals.

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.

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'.

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}?


回答1:


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;
}


来源:https://stackoverflow.com/questions/31977481/can-i-define-a-typescript-class-which-has-an-index-signature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!