Skip to content

Instantly share code, notes, and snippets.

@xperiments
Last active February 13, 2018 22:05
Show Gist options
  • Save xperiments/5930816 to your computer and use it in GitHub Desktop.
Save xperiments/5930816 to your computer and use it in GitHub Desktop.
[[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