简体   繁体   English

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

[英]typescript interface definition with an unknown property key

How to express an interface (IResponse), with one property has a string key (which is not known statically).如何表达一个接口(IResponse),一个属性有一个字符串键(静态未知)。 Below, the key values can be anything like books , chairs , etc. All other keys and types are known statically.下面,关键values可以像任何bookschairs等所有其它的键和类型静态已知。 Below implementation gives error.下面的实现给出了错误。 I guess the error is because the index signature on the IResponse makes all the property values to be IValue[] .我猜这个错误是因为IResponse上的索引签名使所有属性值都是IValue[] Is there a way to do this?有没有办法做到这一点?

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

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

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 (ie 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> resp and <IFunkyResponse> resp to access one or the other of the styles.您可以在<IResponse> resp<IFunkyResponse> resp之间键入断言以访问一种或另一种样式。

Without interface:无接口:

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

There seem to be no exact replies unfortunately, only approximations of a solution.不幸的是,似乎没有确切的答复,只有解决方案的近似值。

The solution is to use intersection type over two interfaces, one that defines static metadata and one that defines dynamic keys:解决方案是在两个接口上使用交集类型,一个定义静态元数据,一个定义动态键:

interface IStatic {
  staticflag: boolean;
}

interface IDynamic {
  [x: string]: string | number;
}

type Complex = IStatic & IDynamic;

const a: Complex = {
  staticflag: false,
  dynamic1: 'a',
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM