Last active
February 13, 2018 22:05
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// => 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