【问题标题】:Possible to define indexer interface for number[]?可以为 number[] 定义索引器接口吗?
【发布时间】:2012-10-16 00:09:08
【问题描述】:

尝试使用定义索引器的接口并将其与系统类型编号 [] 一起使用时,我偶然发现了一些困难。该接口的原因是我希望能够传递具有数字索引器而不是返回数字的任何类型,就像 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。如果我只是搞砸了一些事情,请帮我看看我的错误。如果没有,您能想出一个解决方法吗?

【问题讨论】:

  • 听起来像个 bug,你最好在 CodePlex 上开一张票。

标签: typescript


【解决方案1】:

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

【讨论】:

  • 如果有人搜索这个,我已经在项目页面上提交了this entry
  • 现在跟进,该条目已在最新源中标记为已解决。
【解决方案2】:

我想如果您实际运行它,它会完美运行,但从技术上讲,IIndexedNumeric 是与 number[] 不同的类型,即使它们看起来非常相似。您可能必须将 ary 转换为 IIndexedNumeric 以使编译器不会抱怨。

【讨论】:

  • 强制转换 [1,2,3] 也会失败,并显示“无法将数字 [] 转换为 IIndexedNumeric”。我知道代码将按预期运行,但如果我在调用函数时必须使用 进行强制转换,则它违背了使用类型化接口的目的。
猜你喜欢
  • 1970-01-01
  • 2012-03-24
  • 2019-02-14
  • 1970-01-01
  • 2020-04-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多