← 中文资源

简体中文版本

用 util.types 做运行时类型检查

typeof 与 instanceof 分不出的形态交给 util.types:thenable 不是平台 Promise、ISO 串不是 Date、async 函数与返回 Promise 的普通函数也能区分。

阅读英文原文

实现说明

逻辑集中在函数 load、fakeAsync里。 await 点把异步工作排成序列,拒绝落在取结果的那一行。导入清单标出了平台接触面:types,全部来自 node:util。

使用要点

  • 唯一的导入 node:util 属于 Node.js 标准库。
  • 每一步打印都带着自己的标签:isPromise(Promise):、thenable isPromise:、isDate(new Date()):。

常见问题

运行之前需要装什么吗?

什么都不用装:node:util 随 Node.js 本体提供。

主要签名是 async function load()

核心语句

return Promise.resolve(2);
const thenable = { then: (resolve) => resolve(1) };

代码示例

// 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);