typescript – 可以为number []定义索引器接口吗?

我试图使用定义索引器的接口并将其与系统类型号[]一起使用时遇到了一些困难.接口的原因是我希望能够传递任何具有数字索引器的类型而不是返回数字,就像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关于此.

点赞