gpt4 book ai didi

typescript - 可以为 number[] 定义索引器接口(interface)吗?

转载 作者:搜寻专家 更新时间:2023-10-30 21:00:41 25 4
gpt4 key购买 nike

我在尝试使用定义索引器的接口(interface)并将其与系统类型 number[] 一起使用时遇到了一些困难。使用该接口(interface)的原因是我希望能够传递任何具有数字索引器的类型而不是返回数字,就像 number[] 和类型化数组实例一样。

考虑:

interface IIndexedNumeric
{
[index: number]: number;
}

class buffer {
// ...
push(vals: IIndexedNumeric) { ... }
}

// problem usage:
var ary: number[] = [1,2,3];
var foo = new buffer();

foo.push(ary); // error
// Supplied parameters do not match any signature of call target:
// Could not apply type 'IIndexedNumeric' to argument 1, which is of type 'number[]'

这应该发生吗?看起来 number[] 应该在结构上完全实现 IIndexedNumeric。如果我只是搞砸了某些事情,请帮我看看我的错误。如果没有,您能想出解决方法吗?

最佳答案

我不完全确定,但我相信这是一个错误。规范指出,数组类型文字等同于具有索引签名的对象类型 [index: number]: ElementType,其中 ElementType 在您的例子中是数字。数组类型具有与 Array.prototype.* 相对应的附加属性,但这不应影响仅与索引器的分配兼容性。如果愿意,请file a bug on CodePlex关于这个。

关于typescript - 可以为 number[] 定义索引器接口(interface)吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13074851/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com