[英]How to configure the compiler to implicitly use `unknown` instead of `any` in cases where it fails to infer type information?
There's the compiler option noImplicitAny
, which is described this way:有编译器选项
noImplicitAny
,它是这样描述的:
In some cases where no type annotations are present, TypeScript will fall back to a type of
any
for a variable when it cannot infer the type.在某些不存在类型注释的情况下,TypeScript 在无法推断类型时将回退到变量的
any
类型。This can cause some errors to be missed, for example:
这可能会导致遗漏一些错误,例如:
function fn(s) { // No error? console.log(s.subtr(3)); } fn(42);
Turning on
noImplicitAny
however TypeScript will issue an error whenever it would have inferredany
:打开
noImplicitAny
但是 TypeScript 会在它推断出any
时发出错误:function fn(s) { /* ~ Parameter 's' implicitly has an 'any' type. */ console.log(s.subtr(3)); }
What I want is to configure the compiler to act even more strictly where type information cannot be inferred in cases like the above: I want it to use unknown
at every one of these sites (instead of any
).我想要的是将编译器配置为在上述情况下无法推断出类型信息时采取更严格的操作:我希望它在这些站点中的每一个(而不是
any
)上都使用unknown
。 There's another compiler option useUnknownInCatchVariables
, which is described this way:还有另一个编译器选项
useUnknownInCatchVariables
,它是这样描述的:
In TypeScript 4.0, support was added to allow changing the type of the variable in a catch clause from
any
tounknown
.在 TypeScript 4.0 中,添加了支持以允许将 catch 子句中的变量类型从
any
更改为unknown
。 Allowing for code like:允许这样的代码:
try { //... } catch (err) { // We have to verify err is an // error before using it as one. if (err instanceof Error) { console.log(err.message); } }
This pattern ensures that error handling code becomes more comprehensive because you cannot guarantee that the object being thrown is a Error subclass ahead of time.
这种模式确保错误处理代码变得更加全面,因为您无法保证抛出的 object 是提前的 Error 子类。 With the flag
useUnknownInCatchVariables
enabled, then you do not need the additional syntax (: unknown
) nor a linter rule to try enforce this behavior.启用标志
useUnknownInCatchVariables
后,您不需要额外的语法 (: unknown
) 也不需要 linter 规则来尝试强制执行此行为。
However, that only applies to the exception
parameter in a catch
clause.但是,这仅适用于
catch
子句中的exception
参数。
How can the compiler be configured to fall back to unknown
in all cases?如何将编译器配置为在所有情况下都回退到
unknown
状态?
At the current time, it's not possible to enable this kind of implicit stricter type safety, but an implicitUnknown
option has been suggested at ms/TS#27265 .目前,不可能启用这种隐式更严格的类型安全,但ms/TS#27265中建议了一个
implicitUnknown
选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.