打字稿数组与编号索引和自定义属性交互,可通过字符串键访问 [英] Typescript array interace with numbered index and custom properties accessbile by string keys

查看:15
本文介绍了打字稿数组与编号索引和自定义属性交互,可通过字符串键访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有由数字索引的对象数组,并将所有对象放在特定键下的数组中

I would like to have array of objects indexed by numbers and and also to put all of the objects on the array under specific key

像这样:

const myArray:ICustomArray = []
myArray.push(item)
myArray[item.key] = item;

但我正在努力定义它的界面.首先,我预计这样的事情会起作用,但它不会.

But I am struggling to define its interface. First I expected something like this will work but it does not.

export interface ICustomArray extends Array<IItem> {
  [index: number] : IItem;
  [key: string] : IItem;

}

推荐答案

你的类型的问题是字符串索引签名不一致 ([key: string] : IItem;).如果您继承数组,并非所有以这种方式访问​​的键都属于 IItem 类型.例如 myArray['map'] 将是数组函数而不是 IItem.这就是 typescript 强制字符串索引签名与接口的所有静态声明成员兼容的原因.

The problem with your type is that it is inconsistent with regard to the string index signature ([key: string] : IItem;). Not all keys accessed this way will be of type IItem if you inherit array. For example myArray['map'] will be the array function not IItem. This is the reason typescript forces the string index signature to be compatible with ALL statically declared members of the interface.

这个检查有一个漏洞.交叉型漏洞.我们可以将 ICustomArray 声明为数组和具有索引签名的类型的交集.

There is a loophole in this check though. The intersection type loophole. We can declare ICustomArray as an intersection of array and a type that has the index signature.

export type ICustomArray = Array<IItem> & {
  [key: string] : IItem;
}

let item: IItem;
const myArray: ICustomArray = [] as ICustomArray
myArray.push(item)
myArray[item.key] = item;

这将主要以您期望的方式工作:

This will mostly have work the way you would expect:

let o = myArray['map'] // o is a function of type  <U>(callbackfn: (value: IItem, index: number, array: IItem[]) => U, thisArg?: any) => U[]
let i = myArray['key'] //IItem
declare let randomStr: string
let d = myArray[randomStr] //IItem .. but if randomStr= map, we have a runtime problem

这篇关于打字稿数组与编号索引和自定义属性交互,可通过字符串键访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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