首页  >  文章  >  web前端  >  TypeScript 严格类型 - 部分完整静态类型

TypeScript 严格类型 - 部分完整静态类型

王林
王林原创
2024-08-01 01:51:22820浏览

TypeScript strictly typed - Part full static types

在本系列文章的前一部分中,我们讨论了安全可空性。

现在我们将解释并解决 TypeScript 默认行为的第三个问题,也是最后一个问题:动态类型的剩余部分

我们将涵盖:

  • 动态类型的遗迹
  • 实际平等检查
  • 条件中没有隐式转换
  • 条件简写符号
  • 字符串和数字不能混合

动态类型的残余

TypeScript 应该是一个“静态类型检查器”,与 JavaScript 不同,JavaScript 中的类型是深度动态的。

但在本系列文章的前一部分中,我们还解释了 TypeScript 是作为 JavaScript 的超集构建的。

所以问题是:JavaScript 动态类型系统的某些部分仍然保留在 TypeScript 中。因此,我们将解释如何抑制这些剩余行为以实现完全静态类型

实际平等检查

  • ESLint:eqeqeq
  • 生物群落:可疑.noDoubleEquals(推荐)

这个问题最好的例子是相等性检查。在 JavaScript 中,== 并不完全是相等检查,而是等价检查:

1 == "1"; // true

尽管类型不同,但一些转换规则会起作用,因此 JavaScript 能够比较值。它可能会导致很多错误,因为规则细节很难记住,有时很奇怪,并且在所有动态语言(例如 PHP)中并不完全相同。

这些等价性检查仅在 JavaScript 等动态类型语言中才有意义。从我们决定使用 TypeScript 的那一刻起,只应使用实际的相等检查(类型和值)。

1 === "1"; // false

eqeqeq lint 规则强制执行它。

来自 Java、C# 或 Rust 等语言的人应该特别小心这个问题,因为 JavaScript 或 TypeScript 中的 == 与这些语言中的含义不同。在 JavaScript 和 TypeScript 中,需要第三个 = 才能实现相同的行为。

条件中没有隐式转换

  • ESLint:@typescript-eslint/strict-boolean-expressions
  • 生物群落:缺少规则

认为现在情​​况安全吗?不幸的是不是,因为转换可以是隐式的:

let tax: number | undefined = 0;

if (tax) {
  console.log("Process payment");
}
if (!tax) {
  throw new Error();
}

上面的例子相当于:

let tax: number | undefined = 0;

if (tax == true) {
  console.log("Process payment");
}
if (tax == false) {
  throw new Error();
}

如您所见,存在隐式 ==,因此仍然会发生转换:0 不等于 true,它相当于 false。因此,尽管税费是有效值,它也会出错。

严格布尔表达式 lint 规则不允许此类隐式条件,并强制执行实际检查:

let tax: number | undefined = 0;

if (tax !== undefined) {
  console.log("Process payment");
}
if (tax === undefined) {
  throw new Error();
}

对于习惯了 JavaScript 快速条件的人来说,这可能是最乏味的规则之一,但从长远来看,这只是在 Java、C# 或 Rust 等其他语言中执行操作的正常方法。

如配置部分所示,禁用allowNumber 和allowString 子选项对于避免所有错误非常重要。

唯一允许的例外是对象和数组:这些情况是安全的,因为与字符串和数字相反,它们没有假值。所以下面的还是可以的:

let movie: Movie | undefined;
if (movie) {}
if (!movie) {}

注意:switch 语句已经安全,因为它们在内部使用 ===。

条件简写

  • ESLint:@typescript-eslint/prefer-nullish-coalescing(在风格类型检查中)
  • 生物群落:缺少规则

严格布尔表达式 lint 规则注意条件检查是类型安全的,但除了 if 之外还有其他条件语法:

const movieRating = userRating || 5;

// Which is a shorter version of:
const movieRating = userRating == true ? userRating : 5;

如果用户评分为 0,则 0 相当于 false,因此评分将为 5 而不是 0。

使用现代 JavaScript 可以避免这种情况:

const movieRating = userRating ?? 5;

// Which is a shorter version of:
const movieRating = userRating !== undefined && userRating !== null
  ? userRating
  : 5;

它可以通过prefer-nullish-coalescing lint规则强制执行。

注意??不应在任何地方使用: ||在使用布尔值时仍然相关。

字符串和数字不能混合

  • ESLint:
    • 首选模板
    • @typescript-eslint/restrict-plus-operands(在推荐类型检查中)
    • @typescript-eslint/restrict-template-expressions(在推荐类型检查中)
  • 生物群落:
    • style.useTemplate(推荐)
    • 缺少其他规则

在 JavaScript 中,+ 运算符既可用于数字的数学加法,也可用于字符串连接。它会导致错误。

"There is " + 3 + 1 + "Matrix movies"; // 31
"There is " + (3 + 1) + "Matrix movies"; // 4

+ 运算符应该保留用于数学加法。或者至少,它应该仅用于相同类型的数据,这是限制加操作数 lint 规则强制执行的。

Template strings from modern JavaScript should be used for string concatenation, which the prefer-template lint rule enforces:

const movie = `Everything everywhere all at once`;
`${movie} is the best movie!`;

Conversely, only strings should be used in template strings, which the restrict-template-expressions lint rule enforces.

If mixing types is what is actually wanted, conversions should be explicit:

const total = 3;
`There is ${total.toFixed()} Matrix movies`;

Note that template strings can be nested:

const total = 3;
`There is ${total.toFixed()} Matrix movie${total > 1 ? "s" : ""}`;

Conclusion

This is the end of this posts series. You can follow my account (button on top right of this page) to know when other posts about TypeScript or other topics like Angular are published.

You want to contact me? Instructions are available in the summary.

以上是TypeScript 严格类型 - 部分完整静态类型的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn