具有未知属性键的typescript接口定义

bsr*_*bsr 9 typescript

如何表达一个接口(IResponse),一个属性有一个字符串键(静态不知道).下面,键values可以是任何类似的books,chairs等等.所有其他键和类型都是静态已知的.以下实现给出错误.我猜错误是因为索引签名IResponse使所有属性值成为IValue[].有没有办法做到这一点?

export interface IMeta{}
export interface IValue{}
export interface IResponse {
     meta: IMeta;
     [index: string]:IValue[];
}

 export class Response implements IResponse {
    meta:IMeta;
    values:IValue[];
    //books:IValue[];
    //anything:IValue[];
 }
Run Code Online (Sandbox Code Playgroud)

laa*_*som 8

老问题,但这是我如何为自己解决问题.

export interface Foo {
    [key: string]: any;
}

{ something: 0 } as Foo => valid

{ other: 'hello' } as Foo => valid
Run Code Online (Sandbox Code Playgroud)

  • 这应该是选定的答案。谢谢你的分享! (3认同)

Fen*_*ton 6

如果为已知类型定义一个接口,为“未知”类型定义一个单独的接口,则可以使用类型断言来告诉编译器您要使用的接口。

这不是理想的选择,但是您正在处理极端情况(即,不是完全动态的,不是完全静态的)。

export interface IMeta{}
export interface IValue{}
export interface IFunkyResponse {
     [index: string]:IValue[];
}
export interface IResponse {
     meta: IMeta;
}

export class Response implements IResponse {
    meta:IMeta;
    values:IValue[];
    books:IValue[];
    anything:IValue[];
}
Run Code Online (Sandbox Code Playgroud)

您可以在<IResponse> resp和之间键入断言,<IFunkyResponse> resp以访问一种或另一种样式。