I'm curious about determining the expected type of a typed array:
let A1:string[] = [],
A2:Date[] = [],
expectedType = (arr:any[]) => {
console.log("Expecting: " + /*some magic*/);
};
expectedType(A1); // prints string
expectedType(A2); // prints Date
UPDATE: As mentioned in the response, currently there isn't a way to know the declared types of array members in TypeScript. However, you can implement something like this:
class StrictArray extends Array {
private _expectedType: {new(): T}; // constructor type definition
get expectedType():{new(): T} {return this._expectedType;};
constructor(ctype: {new(): T}, args?:any) {
super.constructor(args);
}
//...
push(t:any) {
if (!(t.constructor !== this._expectedType))
throw "Not valid type";
return super.push(t);
}
}
Now we have objects that act like regular arrays, but we can access and manage their members' types.
Applying it to our example:
let A1:StrictArray = new StrictArray(string),
A2:StrictArray = new StrictArray(Date);
/*magic = */
A1.expectedType.name; // prints string
A2.expectedType.name; // prints Date
Not sure about the practicality or drawbacks of this approach, feel free to share your thoughts.