实现说明
循环只出现在 for (const [label, value] of samples),它的每次迭代处理一个元素。异步流被 await 线性化,失败处理保持局部。导入清单标出了平台接触面:isDate、isRegExp、isPromise,全部来自 node:util/types。
顶层就这几处状态:samples。
使用要点
- 依赖面只有
node:util/types,而它内置于 Node.js。 - 演示输出是带标签的(
narrowed dates:),每个操作都会留下自己的一行标注。
常见问题
它从项目之外导入了什么?
只有 node:util/types,而它是 Node.js 内建的——随运行时提供。
代码示例
// util.types checks internal slots, so look-alike values fail the check and
// the result doubles as a TS type predicate.
import { isDate, isRegExp, isPromise } from 'node:util/types';
const samples = [
['date', new Date('2026-01-01')],
['date-like string', '2026-01-01'],
['regexp', /cache-\d+/],
['regexp-like object', { source: 'cache-\\d+' }],
['promise', Promise.resolve('real')],
['thenable', { then: () => 'fake' }],
] as const;
for (const [label, value] of samples) {
console.log(
label,
'->',
'isDate:', isDate(value),
'isRegExp:', isRegExp(value),
'isPromise:', isPromise(value),
);
}
// The predicate form narrows unknown values without any casting
const values: unknown[] = [
'2026-01-01',
new Date('2026-01-01'),
{ then: () => 'fake' },
Promise.resolve('real'),
];
const dates: Date[] = values.filter(isDate);
console.log('narrowed dates:', dates.length);