1 | # `no-unnecessary-type-assertion`
|
2 |
|
3 | Warns if a type assertion does not change the type of an expression.
|
4 |
|
5 | This rule prohibits using a type assertion that does not change the type of an expression.
|
6 |
|
7 | ## Rule Details
|
8 |
|
9 | This rule aims to prevent unnecessary type assertions.
|
10 |
|
11 | Examples of code for this rule:
|
12 |
|
13 |
|
14 |
|
15 | ### ❌ Incorrect
|
16 |
|
17 | ```ts
|
18 | const foo = 3;
|
19 | const bar = foo!;
|
20 | ```
|
21 |
|
22 | ```ts
|
23 | const foo = <3>3;
|
24 | ```
|
25 |
|
26 | ```ts
|
27 | type Foo = 3;
|
28 | const foo = <Foo>3;
|
29 | ```
|
30 |
|
31 | ```ts
|
32 | type Foo = 3;
|
33 | const foo = 3 as Foo;
|
34 | ```
|
35 |
|
36 | ```ts
|
37 | function foo(x: number): number {
|
38 | return x!; // unnecessary non-null
|
39 | }
|
40 | ```
|
41 |
|
42 | ### ✅ Correct
|
43 |
|
44 | ```ts
|
45 | const foo = <number>3;
|
46 | ```
|
47 |
|
48 | ```ts
|
49 | const foo = 3 as number;
|
50 | ```
|
51 |
|
52 | ```ts
|
53 | const foo = 'foo' as const;
|
54 | ```
|
55 |
|
56 | ```ts
|
57 | function foo(x: number | undefined): number {
|
58 | return x!;
|
59 | }
|
60 | ```
|
61 |
|
62 | ## Options
|
63 |
|
64 | This rule optionally takes an object with a single property `typesToIgnore`, which can be set to a list of type names to ignore.
|
65 |
|
66 | For example, with `@typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }]`, the following is **correct** code":
|
67 |
|
68 | ```ts
|
69 | type Foo = 3;
|
70 | const foo: Foo = 3;
|
71 | ```
|
72 |
|
73 | ## When Not To Use It
|
74 |
|
75 | If you don't care about having no-op type assertions in your code, then you can turn off this rule.
|
76 |
|
77 | ## Related To
|
78 |
|
79 | - TSLint: [`no-unnecessary-type-assertion`](https://palantir.github.io/tslint/rules/no-unnecessary-type-assertion/)
|
80 |
|
81 | ## Attributes
|
82 |
|
83 | - Configs:
|
84 | - [x] ✅ Recommended
|
85 | - [x] 🔒 Strict
|
86 | - [x] 🔧 Fixable
|
87 | - [x] 💭 Requires type information
|