Property is not assignable to string index in interface

五迷三道 提交于 2020-03-17 08:06:39

问题


I have the following interfaces:

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

export interface Api<T> {
  [key: string]: T[];
  meta: Meta; // error
}

Currently, I'm receiving the following error:

Property 'meta' of type 'Meta' is not assignable to string index type 'T[]'.

After searching a bit, I found this statement in TS docs:

While string index signatures are a powerful way to describe the “dictionary” pattern, they also enforce that all properties match their return type. This is because a string index declares that obj.property is also available as obj["property"].

Does it means that when I have a string index signature, I can't have any other variable without match this type?

Actually I can get rid of this error declaring the interface like this:

export interface Api<T> {
  [key: string]: any; // used any here
  meta: Meta;
}

Doing this, I lose the completely ability of type inference. Is there any way to do this without this ugly way?


回答1:


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[]`


来源:https://stackoverflow.com/questions/45258216/property-is-not-assignable-to-string-index-in-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!