Automate reflection-style generic functions
In C#, you can create a generic method that is aware of the generic types.
T As<T>(obj: object)
{
return obj as T;
}
In typescript, you must specify the type twice to accomplish the same.
function as<T>(obj: any, _T: any): T {
return (obj instanceof _T) ? obj : null;
}
It would be nice to automate this for strictly class types (not interfaces since it's not possible).
function as<T>(obj: any): T {
return (obj instanceof T) ? obj : null;
}
TypeScript can't infer the class constructor from the class type, but it can infer the type from the constructor:
function as<T>(obj: any, T: new(...args: any[]) => T): T {
return (obj instanceof T) ? obj : null;
}
var d = as({}, Date); // inferred as type Date
I was posing an example where you would have to explicitly specify the generic type T.
var obj = new Date();
var d = as<Date>(obj);
The problem is there's no 1:1 correspondence between types and the constructor functions that make them. This is similar to #204 in that we don't have any way to know that the Date constructor function was actually the creator of the Date type.