UNPKG

2.44 kBMarkdownView Raw
1# `method-signature-style`
2
3Enforces using a particular method signature syntax.
4
5There are two ways to define an object/interface function property.
6
7```ts
8// method shorthand syntax
9interface T1 {
10 func(arg: string): number;
11}
12
13// regular property with function type
14interface T2 {
15 func: (arg: string) => number;
16}
17```
18
19A good practice is to use the TypeScript's `strict` option (which implies `strictFunctionTypes`) which enables correct typechecking for function properties only (method signatures get old behavior).
20
21TypeScript FAQ:
22
23> A method and a function property of the same type behave differently.
24> Methods are always bivariant in their argument, while function properties are contravariant in their argument under `strictFunctionTypes`.
25
26See the reasoning behind that in the [TypeScript PR for the compiler option](https://github.com/microsoft/TypeScript/pull/18654).
27
28## Options
29
30This rule accepts one string option:
31
32- `"property"`: Enforce using property signature for functions. Use this to enforce maximum correctness together with TypeScript's strict mode.
33- `"method"`: Enforce using method signature for functions. Use this if you aren't using TypeScript's strict mode and prefer this style.
34
35The default is `"property"`.
36
37### `property`
38
39Examples of code with `property` option.
40
41<!--tabs-->
42
43#### ❌ Incorrect
44
45```ts
46interface T1 {
47 func(arg: string): number;
48}
49type T2 = {
50 func(arg: boolean): void;
51};
52interface T3 {
53 func(arg: number): void;
54 func(arg: string): void;
55 func(arg: boolean): void;
56}
57```
58
59#### ✅ Correct
60
61```ts
62interface T1 {
63 func: (arg: string) => number;
64}
65type T2 = {
66 func: (arg: boolean) => void;
67};
68// this is equivalent to the overload
69interface T3 {
70 func: ((arg: number) => void) &
71 ((arg: string) => void) &
72 ((arg: boolean) => void);
73}
74```
75
76### `method`
77
78Examples of code with `method` option.
79
80<!--tabs-->
81
82#### ❌ Incorrect
83
84```ts
85interface T1 {
86 func: (arg: string) => number;
87}
88type T2 = {
89 func: (arg: boolean) => void;
90};
91```
92
93#### ✅ Correct
94
95```ts
96interface T1 {
97 func(arg: string): number;
98}
99type T2 = {
100 func(arg: boolean): void;
101};
102```
103
104## When Not To Use It
105
106If you don't want to enforce a particular style for object/interface function types, and/or if you don't use `strictFunctionTypes`, then you don't need this rule.
107
108## Attributes
109
110- Configs:
111 - [ ] ✅ Recommended
112 - [ ] 🔒 Strict
113- [x] 🔧 Fixable
114- [ ] 💭 Requires type information