deno.com

有效的 typeof

注意:此规则属于 recommended 规则集。
deno.json 中启用完整集合
{
  "lint": {
    "rules": {
      "tags": ["recommended"]
    }
  }
}
使用 Deno CLI 启用完整集合
deno lint --rules-tags=recommended
通过将其添加到 deno.json 中的 includeexclude 数组,可以将此规则明确地包含或排除在当前标签中存在的规则之外。
{
  "lint": {
    "rules": {
      "include": ["valid-typeof"],
      "exclude": ["valid-typeof"]
    }
  }
}

限制 typeof 运算符的使用,使其仅限于特定的字符串字面量。

当与某个值一起使用时,typeof 运算符会返回以下字符串之一:

  • "undefined"
  • "object"
  • "boolean"
  • "number"
  • "string"
  • "function"
  • "symbol"
  • "bigint"

此规则禁止在使用 typeof 运算符时与除这些字符串字面量之外的任何内容进行比较,因为这很可能表示字符串中的拼写错误。该规则还禁止将 typeof 操作的结果与任何非字符串字面量值进行比较,例如 undefined,这可能表示意外地使用了关键字而不是字符串。这包括比较字符串变量,即使它们包含上述值之一,因为这无法保证。一个例外是比较两个 typeof 操作的结果,因为它们都保证会返回上述字符串之一。

无效示例

// typo
typeof foo === "strnig";
typeof foo == "undefimed";
typeof bar != "nunber";
typeof bar !== "fucntion";

// compare with non-string literals
typeof foo === undefined;
typeof bar == Object;
typeof baz === anotherVariable;
typeof foo == 5;

有效示例

typeof foo === "undefined";
typeof bar == "object";
typeof baz === "string";
typeof bar === typeof qux;

您找到所需内容了吗?

隐私政策