Last active
November 7, 2025 02:32
-
-
Save jcayzac/dab5c69f75018f59ae751e78b9572074 to your computer and use it in GitHub Desktop.
Get the type name of anything
This file contains hidden or 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
| function getTypeName(x: unknown): string { | |
| return x === undefined ? 'Undefined' : x === null ? 'Null' : /^(?:class|function) (\w+)/.exec(x.constructor.toString())![1] | |
| } | |
| // Better? function Foo yields 'Function', class Foo yields 'Foo' | |
| function getTypeName(x: unknown): string { | |
| return ( | |
| x === undefined ? 'Undefined' : | |
| x === null ? 'Null' : | |
| /^(?:class) (\w+)/.exec(x.toString())?.[1] ?? | |
| /^(?:function) (\w+)/.exec(x.constructor.toString())?.[1] ?? | |
| (() => { throw new Error(`Not a known type: ${x}`) })() | |
| ) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment