TypeScript 3.0 引入unknown
根据他们的 wiki 输入:
未知现在是保留类型名称,因为它现在是内置类型。
有什么区别unknown
和any
?unknown
超过any
?
答案
您可以阅读更多有关unknown
在里面公关或者RC公告,但其要点是:
[..] 未知哪一个是 any 的类型安全对应项。
举几个例子:
let vAny: any = 10; // We can assign anything to any
let vUnknown: unknown = 10; // We can assign anything to unknown just like any
let s1: string = vAny; // Any is assignable to anything
let s2: string = vUnknown; // Invalid; we can't assign vUnknown to any other type (without an explicit assertion)
vAny.method(); // Ok; anything goes with any
vUnknown.method(); // Not ok; we don't know anything about this variable
建议的用法是:
很多时候我们想要描述 TypeScript 中能力最差的类型。