Property is not assignable to string index in interface

前端 未结 2 1056
后悔当初
后悔当初 2021-02-05 03:05

I have the following interfaces:

export interface Meta {
  counter: number;
  limit: number;
  offset: number;
  total: number;
}

export interface Api          


        
相关标签:
2条回答
  • 2021-02-05 03:09

    You can use an intersection of two interfaces:

    interface Api<T> {
        [key: string]: T[];  
    }
    
    type ApiType<T> = Api<T> & {
        meta: Meta;
    }
    
    declare let x: ApiType<string>;
    
    let a = x.meta // type of `a` is `Meta`
    let b = x["meta"]; // type of `b` is `Meta`
    
    let p = x["someotherindex"] // type of `p` is `string[]`
    let q = x.someotherindex // type of `q` is `string[]`
    
    0 讨论(0)
  • 2021-02-05 03:15

    The presented best solution didn't work when I've tried to implement this interface. I ended up nesting part with dynamic key. Maybe someone will find it useful:

    interface MultichannelConfiguration {
      channels: {
        [key: string]: Configuration;
      }
      defaultChannel: string;
    }
    
    0 讨论(0)
提交回复
热议问题