Skip to content
← Back to rules

typescript/no-inferrable-types 风格

An auto-fix is available for this rule.

它的作用

禁止对初始化为数字、字符串或布尔值的变量或参数进行显式类型声明

为什么这是个问题?

对已初始化为字面量值的变量或参数进行显式类型声明是不必要的,因为 TypeScript 可以从值中推断出类型。

示例

此规则的 错误 代码示例:

ts
const a: number = 5;
const b: string = "foo";
const c: boolean = true;
const fn = (a: number = 5, b: boolean = true, c: string = "foo") => {};

此规则的 正确 代码示例:

ts
const a = 5;
const b = "foo";
const c = true;
const fn = (a = 5, b = true, c = "foo") => {};

配置

此规则接受一个配置对象,包含以下属性:

ignoreParameters

type: boolean

默认值: false

设置为 true 时,忽略函数参数上的类型注解。

ignoreProperties

type: boolean

默认值: false

设置为 true 时,忽略类属性上的类型注解。

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "rules": {
    "typescript/no-inferrable-types": "error"
  }
}
bash
oxlint --deny typescript/no-inferrable-types

参考资料