Skip to main content

prefer-function-type

Enforce using function types instead of interfaces with call signatures.

🎨

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

🔧

此规则报告的一些问题可通过 --fix ESLint 命令行选项自动修复

TypeScript 允许使用两种常见的方法来声明函数的类型:

¥TypeScript allows for two common ways to declare a type for a function:

  • 功能类型:() => string

    ¥Function type: () => string

  • 带有签名的对象类型:{ (): string }

    ¥Object type with a signature: { (): string }

如果可能更简洁,通常优选函数类型形式。

¥The function type form is generally preferred when possible for being more succinct.

此规则建议使用函数类型而不是具有单个调用签名的接口或对象类型字面量。

¥This rule suggests using a function type instead of an interface or object type literal with a single call signature.

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

在线运行试试这个规则 ↗

示例

¥Examples

interface Example {
(): string;
}
Open in Playground
function foo(example: { (): number }): number {
return example();
}
Open in Playground
interface ReturnsSelf {
// returns the function itself, not the `this` argument.
(arg: string): this;
}
Open in Playground

选项

该规则不可配置。

何时不使用它

¥When Not To Use It

如果出于风格原因你特别想要使用具有单个调用签名的接口或类型字面量,则可以避免此规则。

¥If you specifically want to use an interface or type literal with a single call signature for stylistic reasons, you can avoid this rule.

此规则有一个已知的边缘情况,有时会在全局增强(例如 interface Function)上触发。这些边缘情况很少见,并且通常是奇怪代码的症状。我们建议你使用 内联 ESLint 禁用注释。参见 #454 了解详情。

¥This rule has a known edge case of sometimes triggering on global augmentations such as interface Function. These edge cases are rare and often symptomatic of odd code. We recommend you use an inline ESLint disable comment. See #454 for details.

'## 资源'