属性不可分配给接口中的字符串索引[重复]

2024-02-09

我有以下接口:

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

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

目前,我收到以下错误:

“Meta”类型的属性“meta”不可分配给字符串索引 输入“T[]”。

经过一番搜索,我发现了这个说法TS docs https://www.typescriptlang.org/docs/handbook/interfaces.html:

虽然字符串索引签名是描述 “字典”模式,它们还强制所有属性匹配 他们的返回类型。这是因为字符串索引声明 obj.property 也可用作 obj["property"]。

这是否意味着当我有字符串索引签名时,我不能有任何其他与此类型不匹配的变量?

实际上我可以像这样声明接口来消除这个错误:

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

这样做,我完全失去了类型推断的能力。有没有办法做到这一点而不用这种丑陋的方式?


您可以使用路口 https://www.typescriptlang.org/docs/handbook/advanced-types.html#intersection-types两个接口:

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[]`
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

属性不可分配给接口中的字符串索引[重复] 的相关文章

随机推荐