The property is not assigned to the string index in the interface
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
}
I am currently getting the following error:
The 'meta' property of type 'Meta' is not assigned to the string index type 'T []'.
After some searching, I found this expression in the TS docs :
While string indexes are a powerful way of describing a Dictionary, they also enforce all properties of their return type. This is because the line index declares that obj.property is also available as obj ["property"].
Does this mean that when I have a string index signature, I cannot have another variable without matching that type?
In fact, I can get rid of this error by declaring the interface like this:
export interface Api<T> {
[key: string]: any; // used any here
meta: Meta;
}
By doing this, I completely lose the ability to type inference. Is there a way to do this without this ugly way?
source to share
You can use 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[]`
source to share