typescript - 我可以定义一个具有索引签名的 Typescript 类吗?

标签 typescript typescript1.5

我有一个名为 IRawParams 的接口(interface)类型,它简单地指定了一个 string 键和 any 值。

interface IRawParams {
    [key: string]: any
}

我有一个类,ParamValues,它包含键/值之上的一些行为。我想指定 ParamValues 类实现 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;

当我尝试这样做时,出现编译器错误:

error TS2420: Class 'ParamValues' incorrectly implements interface 'IRawParams'. Index signature is missing in type 'ParamValues'.

我能否让我的类实现 IRawParams 接口(interface),或者让 Typescript 允许我的类的实例与索引类型 {[key: string]: any} 兼容?

最佳答案

要定义一个带有索引签名的类,只需在类中写入索引签名即可:

interface IRawParams {
    [key: string]: any
}

class Foo implements IRawParams {
    [k: string]: any;
}

关于typescript - 我可以定义一个具有索引签名的 Typescript 类吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31977481/

相关文章:

javascript - 如何编写一个函数将数组与不同类型的对象分开分组?

angular - 类型错误 : Cannot read property 'player' of undefined

typescript - TS 装饰器 : Generate properties visible by the compiler

javascript - 使用 TypeScript 1.5 的 Angular 2 服务注入(inject)

typescript - 接口(interface) typescript 的实现

spring - 使用单个请求发送 JSON 和图像。 Angular + Spring 引导

typescript - 泛型函数的返回类型

generics - TypeScript类型参数实现多个接口(interface)

visual-studio-2013 - 在 Visual Studio 2013 中使用 tsconfig.json? (网络项目)

typescript :无法从映射函数返回构造新的 Map()