Skip to main content

no-unnecessary-type-constraint

Disallow unnecessary constraints on generic types.

ESLint 配置 中扩展"plugin:@typescript-eslint/recommended" 可启用此规则。

💡

此规则报告的一些问题可以通过编辑器 建议 手动修复。

TypeScript 中的泛型类型参数 (<T>) 可能是 "constrained" 和 extends 关键字。当没有提供 extends 时,类型参数默认将约束设置为 unknown。因此,对于 anyunknown 来说,extend 是多余的。

¥Generic type parameters (<T>) in TypeScript may be "constrained" with an extends keyword. When no extends is provided, type parameters default a constraint to unknown. It is therefore redundant to extend from any or unknown.

eslint.config.mjs
export default tseslint.config({
rules: {
"@typescript-eslint/no-unnecessary-type-constraint": "error"
}
});

在线运行试试这个规则 ↗

示例

¥Examples

interface FooAny<T extends any> {}

interface FooUnknown<T extends unknown> {}

type BarAny<T extends any> = {};

type BarUnknown<T extends unknown> = {};

class BazAny<T extends any> {
quxAny<U extends any>() {}
}

const QuuxAny = <T extends any>() => {};

function QuuzAny<T extends any>() {}
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果你不关心类型约束的特定样式,或者从不首先使用它们,那么你将不需要此规则。

¥If you don't care about the specific styles of your type constraints, or never use them in the first place, then you will not need this rule.

'## 资源'