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。
如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"options": {
"typeAware": true
},
"rules": {
"typescript/no-unnecessary-type-assertion": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
options: { typeAware: true },
rules: {
"typescript/no-unnecessary-type-assertion": "error",
},
});bash
oxlint --type-aware --deny typescript/no-unnecessary-type-assertion版本
此规则在 v1.12.0 中添加。
