如何阻止从 `any` 隐式转换为更强的类型 [英] How to block implicitly casting from `any` to a stronger type

查看:54
本文介绍了如何阻止从 `any` 隐式转换为更强的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 of any as a type declaration. Use this to stop declarations from including any in them, e.g. let data: any = {/*...*/}.
  • no-unsafe-any: Disallows accidentally using any in an unsafe way. This is different from no-any in that you might still be using any types without knowing it: for example, let data = JSON.parse("{}");.

这篇关于如何阻止从 `any` 隐式转换为更强的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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