gpt4 book ai didi

typescript - “未知”与 'any'

转载 作者:搜寻专家 更新时间:2023-10-30 20:28:42 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com