prefer-function-type
Enforce using function types instead of interfaces with call signatures.
Extending "plugin:@typescript-eslint/stylistic"
in an ESLint configuration enables this rule.
Some problems reported by this rule are automatically fixable by the --fix
ESLint command line option.
TypeScript allows for two common ways to declare a type for a function:
- Function type:
() => 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.
module.exports = {
"rules": {
"@typescript-eslint/prefer-function-type": "error"
}
};
Examples
- ❌ Incorrect
- ✅ Correct
interface Example {
(): string;
}
function foo(example: { (): number }): number {
return example();
}
interface ReturnsSelf {
// returns the function itself, not the `this` argument.
(arg: string): this;
}
type Example = () => string;
function foo(example: () => number): number {
return bar();
}
// returns the function itself, not the `this` argument.
type ReturnsSelf = (arg: string) => ReturnsSelf;
function foo(bar: { (): string; baz: number }): string {
return bar();
}
interface Foo {
bar: string;
}
interface Bar extends Foo {
(): void;
}
// 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);
Options
This rule is not configurable.
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 disable this rule.
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.