← 中文资源

简体中文版本

双重断言穿过 unknown

类型不相交的直接断言会被 TS2352 拒绝;穿过 unknown 的双重断言可以绕过,但更推荐写真正的类型守卫在运行期验证形状,而不是硬转过去。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

packed value: 42
flat: r-1 undefined
guarded value: 7
guard rejects unchecked shapes: true

实现说明

双重断言穿过 unknown的核心是函数 hasValue。

使用要点

  • 直接运行文件,输出会带上标签,比如 packed value:、flat:、guarded value:——输出的每一行都能指回产生它的那次调用。

常见问题

这份代码可以原样复制进项目使用吗?

可以。粘进去就能运行,中间没有包管理器的事。 文件在加载时定义 hasValue。

主要签名是 function hasValue(value: unknown)

核心语句

return typeof value === 'object' && value !== null && 'value' in value;

代码示例

type LegacyRow = { id: string; packed: { value: number } };

// JSON.parse returns any, so the first cast is a plain narrowing claim
const raw = JSON.parse('{"id":"r-1","packed":{"value":42}}') as LegacyRow;
console.log('packed value:', raw.packed.value);

// Casts between shapes with no overlap are rejected outright:
// const flat = raw as { id: string; value: number }; // TS2352
// The escape hatch routes through unknown, which overlaps with both sides —
// but the compiler cannot check it, so wrong shapes silently read undefined
const flat = raw as unknown as { id: string; value: number };
console.log('flat:', flat.id, flat.value);

// Prefer a guard: verify the shape at runtime instead of asserting it
function hasValue(value: unknown): value is { id: string; value: number } {
  return typeof value === 'object' && value !== null && 'value' in value;
}

const candidate: unknown = { id: 'r-2', value: 7 };
if (hasValue(candidate)) {
  console.log('guarded value:', candidate.value);
}

console.log('guard rejects unchecked shapes:', hasValue(raw) === false);