UNPKG

1.82 kBMarkdownView Raw
1# `no-non-null-asserted-optional-chain`
2
3Disallows using a non-null assertion after an optional chain expression.
4
5## Rule Details
6
7Optional chain expressions are designed to return `undefined` if the optional property is nullish.
8Using non-null assertions after an optional chain expression is wrong, and introduces a serious type safety hole into your code.
9
10Examples of code for this rule:
11
12<!--tabs-->
13
14### ❌ Incorrect
15
16```ts
17/* eslint @typescript-eslint/no-non-null-asserted-optional-chain: "error" */
18
19foo?.bar!;
20foo?.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
25foo?.bar!.baz;
26foo?.bar!();
27foo?.bar!().baz;
28```
29
30### ✅ Correct
31
32```ts
33/* eslint @typescript-eslint/no-non-null-asserted-optional-chain: "error" */
34
35foo?.bar;
36(foo?.bar).baz;
37foo?.bar();
38foo?.bar();
39foo?.bar().baz;
40
41// The following is correct code if you're using TS3.9 or greater
42foo?.bar!.baz;
43foo?.bar!();
44foo?.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
58This rule is not configurable.
59
60## When Not To Use It
61
62If 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