Util Types Runtime Type Checks
Separate platform Promises from thenables, Dates from ISO strings, and async functions from promise-returning functions with node:util types.
Code
// Runtime type checks that typeof and instanceof cannot express, from node:util types
import { types } from "node:util";
console.log("isPromise(Promise):", types.isPromise(new Promise(() => {})));
// A thenable is NOT a platform Promise, even though await accepts it
const thenable = { then: (resolve) => resolve(1) };
console.log("thenable isPromise:", types.isPromise(thenable), "| has then:", "then" in thenable);
console.log("isDate(new Date()):", types.isDate(new Date()));
console.log("isDate(ISOString):", types.isDate(new Date().toISOString()));
console.log("isMap(new Map()):", types.isMap(new Map()));
console.log("isMap(new WeakMap()):", types.isMap(new WeakMap()));
console.log("isRegExp(literal):", types.isRegExp(/ab/g));
async function load() {
return 1;
}
function fakeAsync() {
return Promise.resolve(2);
}
console.log("isAsyncFunction(load):", types.isAsyncFunction(load));
console.log("isAsyncFunction(fakeAsync):", types.isAsyncFunction(fakeAsync));
console.log("both return promises:", load() instanceof Promise, fakeAsync() instanceof Promise);How the snippet works
All of the logic lives in the functions load and fakeAsync.
Await points sequence the asynchronous work; a rejection lands at the awaiting line. The import names the platform contact area: types, all from node:util.
Points of care
node:utilresolves inside Node.js without any package — it is a core module.
Using it
The primary signature is async function load()
The run emits 10 labeled sections — isPromise(Promise):, thenable isPromise:, isDate(new Date()):, isDate(ISOString):, isMap(new Map()):, isMap(new WeakMap()):, isRegExp(literal):, isAsyncFunction(load):, isAsyncFunction(fakeAsync):, both return promises: — one per step.
Key statements
return Promise.resolve(2);
const thenable = { then: (resolve) => resolve(1) };
Interactive Tools for This Topic
FAQ
- Do I need to install anything before running this?
- Nothing needs installing: `node:util` ships with Node.js itself.
Report a problem with this exampleOpens a pre-filled issue on GitHub.