1 | # `no-non-null-asserted-optional-chain`
|
2 |
|
3 | Disallows using a non-null assertion after an optional chain expression.
|
4 |
|
5 | ## Rule Details
|
6 |
|
7 | Optional chain expressions are designed to return `undefined` if the optional property is nullish.
|
8 | Using non-null assertions after an optional chain expression is wrong, and introduces a serious type safety hole into your code.
|
9 |
|
10 | Examples of code for this rule:
|
11 |
|
12 |
|
13 |
|
14 | ### ❌ Incorrect
|
15 |
|
16 | ```ts
|
17 | /* eslint @typescript-eslint/no-non-null-asserted-optional-chain: "error" */
|
18 |
|
19 | foo?.bar!;
|
20 | foo?.bar()!;
|
21 |
|
22 | // Prior to TS3.9, foo?.bar!.baz meant (foo?.bar).baz - i.e. the non-null assertion is applied to the entire chain so far.
|
23 | // For TS3.9 and greater, the non-null assertion is only applied to the property itself, so it's safe.
|
24 | // The following is incorrect code if you're using less than TS3.9
|
25 | foo?.bar!.baz;
|
26 | foo?.bar!();
|
27 | foo?.bar!().baz;
|
28 | ```
|
29 |
|
30 | ### ✅ Correct
|
31 |
|
32 | ```ts
|
33 | /* eslint @typescript-eslint/no-non-null-asserted-optional-chain: "error" */
|
34 |
|
35 | foo?.bar;
|
36 | (foo?.bar).baz;
|
37 | foo?.bar();
|
38 | foo?.bar();
|
39 | foo?.bar().baz;
|
40 |
|
41 | // The following is correct code if you're using TS3.9 or greater
|
42 | foo?.bar!.baz;
|
43 | foo?.bar!();
|
44 | foo?.bar!().baz;
|
45 | ```
|
46 |
|
47 | ## Options
|
48 |
|
49 | ```jsonc
|
50 | // .eslintrc.json
|
51 | {
|
52 | "rules": {
|
53 | "@typescript-eslint/no-non-null-asserted-optional-chain": "error"
|
54 | }
|
55 | }
|
56 | ```
|
57 |
|
58 | This rule is not configurable.
|
59 |
|
60 | ## When Not To Use It
|
61 |
|
62 | If you are not using TypeScript 3.7 (or greater), then you will not need to use this rule, as the operator is not supported.
|
63 |
|
64 | ## Further Reading
|
65 |
|
66 | - [TypeScript 3.7 Release Notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html)
|
67 | - [Optional Chaining Proposal](https://github.com/tc39/proposal-optional-chaining/)
|
68 |
|
69 | ## Attributes
|
70 |
|
71 | - Configs:
|
72 | - [x] ✅ Recommended
|
73 | - [x] 🔒 Strict
|
74 | - [ ] 🔧 Fixable
|
75 | - [ ] 💭 Requires type information
|