Skip to content

Instantly share code, notes, and snippets.

@jcayzac
Last active November 7, 2025 02:32
Show Gist options
  • Select an option

  • Save jcayzac/dab5c69f75018f59ae751e78b9572074 to your computer and use it in GitHub Desktop.

Select an option

Save jcayzac/dab5c69f75018f59ae751e78b9572074 to your computer and use it in GitHub Desktop.
Get the type name of anything
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