如何阻止从 `any` 隐式转换为更强的类型 [英] How to block implicitly casting from `any` to a stronger type
问题描述
TypeScript 允许从 any
隐式转换为更强的类型.考虑到反序列化的 JSON 是 any
类型,这种行为会导致许多类型错误并破坏类型.
TypeScript allows implicitly casting from any
to a stronger type. Considering deserialized JSON is of type any
, this behavior allows many type errors and breaks typings.
我可以使用哪些编译器或 linting 选项来阻止从 any
隐式转换为更强的类型?
What compiler or linting options can I use to block implicitly casting from any
to a stronger type?
Repro 应标记此操作以允许从 any
转换为更强的类型.
Repro This operation should be flagged for allowing casting from any
to a stronger type.
const o = JSON.parse("");
const s: string = o.twinlakes;
推荐答案
如果您还没有,请尝试启用 TypeScript --noImplicitAny
编译器标志,以防止声明意外忘记标记无法推断的事物类型.这将阻止诸如 let data;
或 function takeData(data) {/* ... */}
之类的代码允许它们的 data
隐式"变量类型为 any
.
If you haven't yet, try enabling the TypeScript --noImplicitAny
compiler flag to stop declarations from accidentally forgetting to mark types of things that can't be inferred. This'll stop code such as let data;
or function takesData(data) { /* ... */ }
from allowing their data
variables to "implicitly" be type any
.
此外,还有一些 TSLint 规则在这里有帮助:
Additionally, there are a couple TSLint rules that help here:
no-any
:禁止使用any
作为类型声明.使用它来阻止声明中包含any
,例如let data: any = {/*...*/}
.no-unsafe-any
:禁止以不安全的方式意外使用any
.这与no-any
不同,因为您可能仍在使用any
类型而不知道它:例如,let data = JSON.parse("{}");
.
no-any
: Disallows usages ofany
as a type declaration. Use this to stop declarations from includingany
in them, e.g.let data: any = {/*...*/}
.no-unsafe-any
: Disallows accidentally usingany
in an unsafe way. This is different fromno-any
in that you might still be usingany
types without knowing it: for example,let data = JSON.parse("{}");
.
这篇关于如何阻止从 `any` 隐式转换为更强的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!