Skip to content

Unknown 类型

一句话解释

unknown 类型接受任何值 但需要类型 narrowing 之前 use, 制作它 类型-safe alternative 到任何.

用大白话说

unknown 类型是 类型-safe version 的 any. 如 any, 它接受任何值. Unlike any, you cannot use the value without first narrowing the type — you must check it with typeof, instanceof, or a type guard.

This makes unknown much safer for handling untrusted data like JSON.parse results, API responses, and user input. It forces you to verify the type before using it, preventing runtime errors.

Prefer unknown over 任何 whenever possible. Use 任何 only when you genuinely need to opt out of type checking (which should be rare). The unknown type was added in TypeScript 3.0.

示例

typescript
const data: unknown = JSON.parse("{}");
// data.name; // Error: Object is of type 'unknown'

if (typeof data === "object" && data !== null) {
  console.log(data); // OK: narrowed to object
}

unknown 需要 narrowing 之前 use, unlike 任何哪个允许所有操作.

常见混淆

  • 容易混淆的对象: 任何

    关键区别: 任何允许所有操作不使用检查; unknown 需要类型 narrowing 首先. unknown 是总是 safer.

相关术语

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表