Reliable Type
Reliable runtime type information.
pnpm install reliable-type
The provided type
method is more reliable than some combination of typeof
and instanceof
. While the .constructor
Object
property is strong
—and recommended, in absence of a dependency like this—it can technically be
reassigned. It will always return
the correct type as an informative,
specific Type or tag
String
. Extra types are also available to import
:
import assert from "node:assert/strict"
import { type, types, tag, tags } from "reliable-type"
import { GeneratorFunction } from "reliable-type/types"
function* generator() { yield * [1, 2, 3] }
const Type = type(generator)
const Tag = tag(generator)
assert.equal(Type, GeneratorFunction)
assert.equal(Tag, "GeneratorFunction")
assert.equal(Type, types.GeneratorFunction)
assert.equal(Tag, tags.GeneratorFunction)
Expression | type |
tag |
---|---|---|
undefined |
undefined |
"undefined" |
null |
null |
"null" |
true /false |
Boolean |
"Boolean" |
"string" |
String |
"String" |
-0 /1_000 /0.1 |
Number |
"Number" |
0xAf /0o1 /0b1 |
Number |
"Number" |
3.1415e+1 /Math.PI |
Number |
"Number" |
1_000_000n |
BigInt |
"BigInt" |
[- ]Infinity |
Infinity |
"Infinity" |
NaN |
NaN |
"NaN" |
Math |
Math |
"Math" |
Symbol("*") |
Symbol |
"Symbol" |
new Intl.Segmenter() |
Segmenter |
"Segmenter" |
new Date() |
Date |
"Date" |
/.*/g /new RegExp(".*") |
RegExp |
"RegExp" |
new URL("https://github.com") |
URL |
"URL" |
const buffer = Buffer.from("data") |
Buffer |
"Buffer" |
fs.createReadStream(buffer) |
ReadStream |
"ReadStream" |
fs.createWriteStream("/dev/null") |
WriteStream |
"WriteStream" |
new Uint8Array([0, 255]) |
Uint8Array |
"Uint8Array" |
[1 ,2 ,3] /Array.from("abc") |
Array |
"Array" |
new Set([1, 2, 3]) |
Set |
"Set" |
new WeakSet() |
WeakSet |
"WeakSet" |
new WeakMap() |
WeakMap |
"WeakMap" |
const map = new Map().set("a", 1) |
Map |
"Map" |
map.entries() |
Iterator |
"Iterator" |
const object = { a: 1, b: 2 } |
Object |
"Object" |
new Proxy(object, {}) |
Proxy |
"Proxy" |
Proxy.revocable(object, {}) |
Proxy |
"Proxy" |
{ [Symbol.toStringTag]: "tag" } |
"tag" |
"tag" |
JSON |
JSON |
"JSON" |
function() { return arguments }(1, 2) |
Arguments |
"Arguments" |
[].reduce /() => {} |
Function |
"Function" |
async () => Promise.resolve(true) |
AsyncFunction |
"AsyncFunction" |
Promise.resolve(true) |
Promise |
"Promise" |
function* generator() { yield * [1, 2] } |
GeneratorFunction |
"GeneratorFunction" |
generator() |
Generator |
"Generator" |
async function* gen() { yield * [1, 2] } |
AsyncGeneratorFunction |
"AsyncGeneratorFunction" |
gen() |
AsyncGenerator |
"AsyncGenerator" |
new (class Class {})() |
Class |
"Class" |
new (class Extended extends Class {})() |
ExtendedClass |
"ExtendedClass" |
fs.opendir(dir) |
Dir |
"Dir" |
fs.readdir(dir, { withFileTypes: true }) |
Dirent |
"Dirent" |
import { typeOf, toStringTag } from "reliable-type"