UNPKG

1.5 kBMarkdownView Raw
1# `no-unnecessary-type-assertion`
2
3Warns if a type assertion does not change the type of an expression.
4
5This rule prohibits using a type assertion that does not change the type of an expression.
6
7## Rule Details
8
9This rule aims to prevent unnecessary type assertions.
10
11Examples of code for this rule:
12
13<!--tabs-->
14
15### ❌ Incorrect
16
17```ts
18const foo = 3;
19const bar = foo!;
20```
21
22```ts
23const foo = <3>3;
24```
25
26```ts
27type Foo = 3;
28const foo = <Foo>3;
29```
30
31```ts
32type Foo = 3;
33const foo = 3 as Foo;
34```
35
36```ts
37function foo(x: number): number {
38 return x!; // unnecessary non-null
39}
40```
41
42### ✅ Correct
43
44```ts
45const foo = <number>3;
46```
47
48```ts
49const foo = 3 as number;
50```
51
52```ts
53const foo = 'foo' as const;
54```
55
56```ts
57function foo(x: number | undefined): number {
58 return x!;
59}
60```
61
62## Options
63
64This rule optionally takes an object with a single property `typesToIgnore`, which can be set to a list of type names to ignore.
65
66For example, with `@typescript-eslint/no-unnecessary-type-assertion: ["error", { typesToIgnore: ['Foo'] }]`, the following is **correct** code":
67
68```ts
69type Foo = 3;
70const foo: Foo = 3;
71```
72
73## When Not To Use It
74
75If 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