prefer-function-type
Enforce using function types instead of interfaces with call signatures.
Extending"plugin:@typescript-eslint/stylistic" in anESLint 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.
- Flat Config
- Legacy Config
exportdefault tseslint.config({
rules:{
"@typescript-eslint/prefer-function-type":"error"
}
});
module.exports={
"rules":{
"@typescript-eslint/prefer-function-type":"error"
}
};
Try this rule in the playground ↗
Examples
- ❌ Incorrect
- ✅ Correct
interfaceExample{
():string;
}
Open in Playgroundfunctionfoo(example:{():number}):number{
returnexample();
}
Open in PlaygroundinterfaceReturnsSelf{
// returns the function itself, not the `this` argument.
(arg:string):this;
}
Open in PlaygroundtypeExample=()=>string;
Open in Playgroundfunctionfoo(example:()=>number):number{
returnbar();
}
Open in Playground// returns the function itself, not the `this` argument.
typeReturnsSelf=(arg:string)=> ReturnsSelf;
Open in Playgroundfunctionfoo(bar:{():string; baz:number}):string{
returnbar();
}
Open in PlaygroundinterfaceFoo{
bar:string;
}
interfaceBarextendsFoo{
():void;
}
Open in Playground// multiple call signatures (overloads) is allowed:
interfaceOverloaded{
(data:string):number;
(id:number):string;
}
// this is equivelent to Overloaded interface.
typeIntersection=((data:string)=>number)&((id:number)=>string);
Open in PlaygroundOptions
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 avoid this rule.
This rule has a known edge case of sometimes triggering on global augmentations such asinterface Function.These edge cases are rare and often symptomatic of odd code.We recommend you use aninline ESLint disable comment.See#454 for details.