typescript/no-unnecessary-type-arguments 可疑
它的作用
此规则禁止使用与默认类型参数相同的类型参数。
为什么这是不好的?
显式声明的类型参数如果与它们的默认值相同,是不必要的,并且会为代码增加视觉噪音。TypeScript 会自动推断这些类型。
示例
此规则的错误代码示例:
ts
function identity<T = string>(arg: T): T {
return arg;
}
// 多余的类型参数 - string 是默认值
const result = identity<string>("hello");
interface Container<T = number> {
value: T;
}
// 多余的类型参数 - number 是默认值
const container: Container<number> = { value: 42 };
class MyClass<T = boolean> {
constructor(public value: T) {}
}
// 多余的类型参数 - boolean 是默认值
const instance = new MyClass<boolean>(true);此规则的正确代码示例:
ts
function identity<T = string>(arg: T): T {
return arg;
}
// 使用默认类型
const result1 = identity("hello");
// 使用不同类型
const result2 = identity<number>(42);
interface Container<T = number> {
value: T;
}
// 使用默认类型
const container1: Container = { value: 42 };
// 使用不同类型
const container2: Container<string> = { value: "hello" };如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"rules": {
"typescript/no-unnecessary-type-arguments": "error"
}
}bash
oxlint --type-aware --deny typescript/no-unnecessary-type-arguments