无法将属性分配给接口中的字符串索引 [英] Property is not assignable to string index in interface

查看:138
本文介绍了无法将属性分配给接口中的字符串索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下界面:

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:

类型元"的属性元"不可分配给字符串索引 输入"T []".

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

经过一番搜索,我在 TS文档中找到了该语句> :

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

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

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?

推荐答案

您可以使用两个界面的交点:

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

这篇关于无法将属性分配给接口中的字符串索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆