您可以通过两种不同的方式进行投射:
var doSomething = function <T>(a: Enumeration<T>) { };
var x: Object[] = [];
// cast using "<>""
doSomething(<Enumeration<Object>>x);
// cast using "as"
doSomething(x as Enumeration<Object>);
但是您Enumeration
可能应该扩展Array
:
interface Enumeration<T> extends Array<T> {
// ...
}
更新
class Enumeration<T> extends Array<T> {
private _cursor: number;
public constructor(...elements: T[]) {
super(...elements);
this._cursor = 0;
}
public nextElement() {
this._cursor = this._cursor + 1;
return this.values[this._cursor];
};
public hasMoreElements() {
return this._cursor < this.length - 1;
}
public static fromArray<T>(arr: T[]) {
return new Enumeration<T>(...arr);
}
}
interface User {
name: string;
}
let a: Array<User> = [{ name: "user1" }, { name: "user2" }];
let b: Enumeration<User> = new Enumeration({ name: "user1" }, { name: "user2" });
a = b; // OK: Enumeration<User> is assignable to Array<User>
b = a; // Error: Array<User> is not assignable to Enumeration<User>
也许您可以fromArray
在枚举类中添加一个方法:
var doSomething = function <T>(a: Enumeration<T>) { };
doSomething(Enumeration.fromArray<User>(a));