Jake H
Jake H

Reputation: 1740

Possible to define indexer interface for number[]?

I have stumbled into some difficulty trying to use an interface that defines an indexer and using it with the system type number[]. The reason for the interface is that I wish to be able to pass any type that has a numeric indexer than returns a number, as is the case for both number[] and also typed array instances.

Consider:

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

Should this occur? It seems that number[] should fully structurally implement IIndexedNumeric. If I've simply botched something, please help me see my error. If not, could you think of a workaround?

Upvotes: 4

Views: 4134

Answers (2)

Brian Terlson
Brian Terlson

Reputation: 9630

I'm not entirely sure but I believe this is a bug. The spec states that an array type literal is equivalent to an object type with an index signature [index: number]: ElementType, where ElementType in your case is number. The array type has additional properties corresponding to Array.prototype.* but this shouldn't affect assignment compatibility with just an indexer. If you would, please file a bug on CodePlex about this.

Upvotes: 2

Richicoder
Richicoder

Reputation: 864

I would imagine that it would work perfectly if you actually ran it, but technically IIndexedNumeric is a different type that number[], even if they look very similar. You'd probably have to cast ary to IIndexedNumeric for the compiler not to complain.

Upvotes: 0

Related Questions