TypeScript 3.0 中新增了一种 unknown 类型。

New unknown top type

unknown is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn’t assignable to anything but itself and any without a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.

简单来说,unknown 是一种更加安全的 any 的副本。所有东西都可以被标记成是 unknown 类型,但是 unkonwn 必须在进行类型判断和条件控制之后才可以被分配成其他类型,并且在类型判断和条件控制之前也不能进行任何操作。

一些常见的使用案例可以参考官方文档

我这边举出一个很常见的使用场景。

假设我们在一个 TypeScript 项目中,引入了一个 JavaScript 编写的库,这个库通过单独的 TypeScript declaration 文件提供 TypeScript 支持,那么就可能存在一种情况。

import { method } from 'js-lib';

const method = (some: SomeType) => void;

method().d.ts 中声明的参数类型是 SomeType,但是它实际接受另一种类型的参数,比如 null

// 如果直接传入 null,那么编译器就会报错
method(null);
// Error: Argument of type 'null' is not assignable to parameter of type 'SomeType'

这种情况下就可以利用 unknown 类型来实现传入 null。

method(null as unknown as SomeType);

这样就可以正常通过编译器的类型校验了。

当然最好还是编写正确的 declaration 文件。