UNPKG

1.89 kBMarkdownView Raw
1# `prefer-function-type`
2
3Use function types instead of interfaces with call signatures.
4
5## Rule Details
6
7This rule suggests using a function type instead of an interface or object type literal with a single call signature.
8
9Examples of code for this rule:
10
11<!--tabs-->
12
13### ❌ Incorrect
14
15```ts
16interface Foo {
17 (): string;
18}
19```
20
21```ts
22function foo(bar: { (): number }): number {
23 return bar();
24}
25```
26
27```ts
28interface Foo extends Function {
29 (): void;
30}
31```
32
33```ts
34interface MixinMethod {
35 // returns the function itself, not the `this` argument.
36 (arg: string): this;
37}
38```
39
40### ✅ Correct
41
42```ts
43interface Foo {
44 (): void;
45 bar: number;
46}
47```
48
49```ts
50function foo(bar: { (): string; baz: number }): string {
51 return bar();
52}
53```
54
55```ts
56interface Foo {
57 bar: string;
58}
59interface Bar extends Foo {
60 (): void;
61}
62```
63
64```ts
65// returns the `this` argument of function, retaining it's type.
66type MixinMethod = <TSelf>(this: TSelf, arg: string) => TSelf;
67// a function that returns itself is much clearer in this form.
68type ReturnsSelf = (arg: string) => ReturnsSelf;
69```
70
71```ts
72// multiple call signatures (overloads) is allowed:
73interface Overloaded {
74 (data: string): number;
75 (id: number): string;
76}
77// this is equivelent to Overloaded interface.
78type Intersection = ((data: string) => number) & ((id: number) => string);
79```
80
81## Options
82
83```jsonc
84// .eslintrc.json
85{
86 "rules": {
87 "@typescript-eslint/prefer-function-type": "warn"
88 }
89}
90```
91
92This rule is not configurable.
93
94## When Not To Use It
95
96If you specifically want to use an interface or type literal with a single call signature for stylistic reasons, you can disable this rule.
97
98## Further Reading
99
100- TSLint: [`callable-types`](https://palantir.github.io/tslint/rules/callable-types/)
101
102## Attributes
103
104- Configs:
105 - [ ] ✅ Recommended
106 - [x] 🔒 Strict
107- [x] 🔧 Fixable
108- [ ] 💭 Requires type information