typescript/no-unnecessary-type-assertion 可疑
它做了什么
此规则禁止那些不会改变表达式类型的操作类型断言。
为什么这是个问题?
不会真正改变表达式类型的类型断言是多余的,可以安全地移除。它们只会增加视觉噪音而没有任何实际好处,可能反映出对 TypeScript 类型系统的理解不清。
示例
以下为 错误 的代码示例:
ts
const str: string = "hello";
const redundant = str as string; // 多余,str 已经是 string 类型
function getString(): string {
return "hello";
}
const result = getString() as string; // 多余,getString() 已经返回 string
const num = 42;
const alsoRedundant = num as 42; // 如果 TypeScript 能推断出字面量类型,则此项多余
// 无意义地将类型扩大
const literal = "hello" as string;以下为 正确 的代码示例:
ts
const unknown: unknown = "hello";
const str = unknown as string; // 必须缩小类型范围
const element = document.getElementById("myElement") as HTMLInputElement; // 必须指定具体元素类型
const obj = { name: "John" };
const name = obj.name as const; // 必须用于字面量类型
// 无需断言
const str2: string = "hello";
const num: number = 42;配置
此规则接受一个配置对象,包含以下属性:
checkLiteralConstAssertions
type: boolean
default: false
是否检查像 'foo' as const 这样的字面量 const 断言。 当为 false(默认值)时,字面量类型的 const 断言不会被标记。 当为 true 时,这些断言会被报告为多余,因为其类型已经是字面量类型。
typesToIgnore
type: string[]
default: []
在检查不必要的断言时忽略的类型名称列表。 即使这些类型断言看起来不必要,也不会被标记。 例如:["Foo", "Bar"] 可允许 x as Foo 或 x as Bar。
如何使用
要通过配置文件或 CLI 启用 此规则,可以使用:
json
{
"rules": {
"typescript/no-unnecessary-type-assertion": "error"
}
}bash
oxlint --type-aware --deny typescript/no-unnecessary-type-assertion