typescript 带有未知属性键的打字稿接口定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23914271/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 02:54:32  来源:igfitidea点击:

typescript interface definition with an unknown property key

typescript

提问by bsr

How to express an interface (IResponse), with one property has a string key (which is not known statically). Below, the key valuescan be anything like books, chairs, etc. All other keys and types are known statically. Below implementationgives error. I guess the error is because the index signature on the IResponsemakes all the property values to be IValue[]. Is there a way to do this?

如何表达一个接口(IResponse),一个属性有一个字符串键(静态未知)。下面,键values可以像任何事情bookschairs等所有其它的键和类型静态已知。下面的实现给出了错误。我猜这个错误是因为 上的索引签名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[];
 }

采纳答案by Fenton

If you define one interface for the known types and a separate one for the "unknown" types, you could use a type assertion to tell the compiler the one you wanted to use.

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

It isn't ideal, but you are working in a edge case (i.e. not entirely dynamic, not entirely static).

这并不理想,但您在边缘情况下工作(即不完全动态,不完全静态)。

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

You can type-assert between <IResponse> respand <IFunkyResponse> respto access one or the other of the styles.

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

回答by Mavrick Laakso

Old question, but here is how I solved the issue for myself.

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

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

{ something: 0 } as Foo => valid

{ other: 'hello' } as Foo => valid

回答by kxo

Without interface:

无接口:

const myFunc = ((myObjectWithSomeKeys: { [key: string]: any }) => {
});