Skip to content

Instantly share code, notes, and snippets.

@xperiments xperiments/new_gist_file
Last active Feb 13, 2018

Embed
What would you like to do?
[[ts] Check if obj is instanceof U] Check if obj is instanceof U
// => http://stackoverflow.com/questions/17392349/how-can-i-check-if-element-is-an-instanceof-u
function OfType<T, U>(list: T[], arg: Function) : U[]
{
var result: U[] = [];
list.forEach(e => {
// extract the name of the class
// used to match primitive types
var typeName = /function\s*([^(]*)/i.exec(arg+"")[1].toLocaleLowerCase();
var isOfType = typeof(e) === typeName;
// if it is not primitive or didn't match the type
// try to check if it is an instanceof
if (!isOfType)
{
try {
isOfType = (e instanceof arg)
}
catch (ex) { }
}
if (isOfType)
result.push(<U><any>e);
});
return <any[]>result;
}
var list: any[] = [];
list.push("A");
list.push(2);
var numbers = OfType<any, number>(list, Number);
alert("Numbers: " + numbers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.