1 | # `prefer-function-type`
|
2 |
|
3 | Use function types instead of interfaces with call signatures.
|
4 |
|
5 | ## Rule Details
|
6 |
|
7 | This rule suggests using a function type instead of an interface or object type literal with a single call signature.
|
8 |
|
9 | Examples of code for this rule:
|
10 |
|
11 |
|
12 |
|
13 | ### ❌ Incorrect
|
14 |
|
15 | ```ts
|
16 | interface Foo {
|
17 | (): string;
|
18 | }
|
19 | ```
|
20 |
|
21 | ```ts
|
22 | function foo(bar: { (): number }): number {
|
23 | return bar();
|
24 | }
|
25 | ```
|
26 |
|
27 | ```ts
|
28 | interface Foo extends Function {
|
29 | (): void;
|
30 | }
|
31 | ```
|
32 |
|
33 | ```ts
|
34 | interface MixinMethod {
|
35 | // returns the function itself, not the `this` argument.
|
36 | (arg: string): this;
|
37 | }
|
38 | ```
|
39 |
|
40 | ### ✅ Correct
|
41 |
|
42 | ```ts
|
43 | interface Foo {
|
44 | (): void;
|
45 | bar: number;
|
46 | }
|
47 | ```
|
48 |
|
49 | ```ts
|
50 | function foo(bar: { (): string; baz: number }): string {
|
51 | return bar();
|
52 | }
|
53 | ```
|
54 |
|
55 | ```ts
|
56 | interface Foo {
|
57 | bar: string;
|
58 | }
|
59 | interface Bar extends Foo {
|
60 | (): void;
|
61 | }
|
62 | ```
|
63 |
|
64 | ```ts
|
65 | // returns the `this` argument of function, retaining it's type.
|
66 | type MixinMethod = <TSelf>(this: TSelf, arg: string) => TSelf;
|
67 | // a function that returns itself is much clearer in this form.
|
68 | type ReturnsSelf = (arg: string) => ReturnsSelf;
|
69 | ```
|
70 |
|
71 | ```ts
|
72 | // multiple call signatures (overloads) is allowed:
|
73 | interface Overloaded {
|
74 | (data: string): number;
|
75 | (id: number): string;
|
76 | }
|
77 | // this is equivelent to Overloaded interface.
|
78 | type 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 |
|
92 | This rule is not configurable.
|
93 |
|
94 | ## When Not To Use It
|
95 |
|
96 | If 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
|