typescript - “未知”与 'any'

标签 typescript typescript3.0

TypeScript 3.0 引入了 unknown 类型,根据他们的 wiki:

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 有什么区别?我们什么时候应该使用 unknown 而不是 any

最佳答案

您可以在 PR 中阅读更多关于 unknown 的信息或 RC announcement ,但它的要点是:

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

建议的用法是:

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.

关于typescript - “未知”与 'any',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439843/

相关文章:

reactjs - typescript 3 : property is missing in type

javascript - 具有 Set 集合的类方法不返回任何内容

node.js - 在 Webpack 中,如何动态设置公共(public)路径?

reactjs - 尝试将调度函数包装在react redux中

typescript - 在 Typescript 中防止不适当的导入和执行项目层次结构

javascript - 在 Typescript 中扩展内置类型

angular - 我什么时候可以检查是否已给出 '@Input()'?

data-binding - Angular2 2 方式绑定(bind)中相同名称的自定义输入和输出

使用函数解析的 Typescript 回调参数

TypeScript 路径映射 "Cannot find module a-mapped/a"