我想将类型的元素添加any
到数组中,然后从该数组中获取数字元素:
function OfType<T, U>(list: T[]) : U[]
{
var result: U[] = [];
list.forEach(e => {
// I want to check if e is of type U
//if (typeof(e) === typeof(U)) // ERROR: doesn't work
result.push(<U><any>e);
});
return <any[]>result;
}
var list: any[] = [];
list.push("A");
list.push(2);
var result = OfType<any, number>(list);
alert(result.toString());
但它不允许我根据泛型类型检查元素的类型。
有没有办法做到这一点?