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
- 带有签名的对象类型:
{ (): 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.
module.exports = {
"rules": {
"@typescript-eslint/prefer-function-type": "error"
}
};
示例
- ❌ 不正确
- ✅ 正确
interface Example {
(): string;
}
Open in Playgroundfunction foo(example: { (): number }): number {
return example();
}
Open in Playgroundinterface ReturnsSelf {
// returns the function itself, not the `this` argument.
(arg: string): this;
}
Open in Playgroundtype Example = () => string;
Open in Playgroundfunction foo(example: () => number): number {
return bar();
}
Open in Playground// returns the function itself, not the `this` argument.
type ReturnsSelf = (arg: string) => ReturnsSelf;
Open in Playgroundfunction foo(bar: { (): string; baz: number }): string {
return bar();
}
Open in Playgroundinterface Foo {
bar: string;
}
interface Bar extends Foo {
(): void;
}
Open in Playground// multiple call signatures (overloads) is allowed:
interface Overloaded {
(data: string): number;
(id: number): string;
}
// this is equivelent to Overloaded interface.
type Intersection = ((data: string) => number) & ((id: number) => string);
Open in Playground何时不使用它
如果出于风格原因你特别想要使用具有单个调用签名的接口或类型字面量,则可以避免此规则。
英: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.
选项
该规则不可配置。