typescript interface definition with an unknown property key

后端 未结 3 406
终归单人心
终归单人心 2021-01-11 14:09

How to express an interface (IResponse), with one property has a string key (which is not known statically). Below, the key values can be anything like bo

相关标签:
3条回答
  • 2021-01-11 14:42

    Without interface:

    const myFunc = ((myObjectWithSomeKeys: { [key: string]: any }) => {
    });
    
    0 讨论(0)
  • 2021-01-11 14:48

    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
    
    0 讨论(0)
  • 2021-01-11 14:56

    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> resp and <IFunkyResponse> resp to access one or the other of the styles.

    0 讨论(0)
提交回复
热议问题