本文介绍了“未知"与“任何"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
TypeScript 3.0根据其Wiki引入了unknown
类型:
TypeScript 3.0 introduces unknown
type, according to their wiki:
unknown
和any
有什么区别?什么时候应该在any
上使用unknown
?
What is difference between unknown
and any
? When should we use unknown
over any
?
推荐答案
You can read more about unknown
in the PR or the RC announcement, but the gist of it is:
一些例子:
let vAny: any = 10; // We can assign anthing to any
let vUnknown: unknown = 10; // We can assign anthing to unknown just like any
let s1: string = vAny; // Any is assigable 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
建议的用法是:
这篇关于“未知"与“任何"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!