“未知"与“任何" [英] 'unknown' vs. 'any'

查看:90
本文介绍了“未知"与“任何"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TypeScript 3.0根据其Wiki引入了unknown类型:

TypeScript 3.0 introduces unknown type, according to their wiki:

unknown现在是保留类型名称,因为它是内置类型. 根据未知的用途,您可能希望删除 完全声明(有利于新引入的未知类型),或 将其重命名为其他名称.

unknown is now a reserved type name, as it is now a built-in type. Depending on your intended use of unknown, you may want to remove the declaration entirely (favoring the newly introduced unknown type), or rename it to something else.

unknownany有什么区别?什么时候应该在any上使用unknown?

What is difference between unknown and any? When should we use unknown over any?

推荐答案

您可以在 PR

You can read more about unknown in the PR or the RC announcement, but the gist of it is:

[..] unknown,它是任何类型安全的副本.任何事物都可以分配给未知对象,但是未知事物不能分配给任何事物,只有它本身以及没有类型声明或没有基于控制流的缩小的任何事物.同样,在未声明或缩小为更具体的类型之前,不允许对未知数执行任何操作.

[..] unknown which 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.

一些例子:

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

建议的用法是:

很多时候,我们想在TypeScript中描述功能最差的类型.这对于希望表示可以是任何值,因此在使用它之前必须执行某种类型的检查"的API很有用.这迫使用户安全地检查返回的值.

There are often times where we want to describe the least-capable type in TypeScript. This is useful for APIs that want to signal "this can be any value, so you must perform some type of checking before you use it". This forces users to safely introspect returned values.

这篇关于“未知"与“任何"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆