You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
/// This rule disallows type assertions using the `any` type.
11
+
/// Disallows unsafe type assertions that narrow a type.
12
12
///
13
13
/// ### Why is this bad?
14
14
///
15
-
/// Type assertions using `any` completely bypass TypeScript's type system and can lead to runtime errors. They should be avoided in favor of more specific type assertions or proper type guards.
15
+
/// Type assertions that narrow a type bypass TypeScript's type-checking and can lead to
16
+
/// runtime errors. Type assertions that broaden a type are safe because TypeScript
17
+
/// essentially knows *less* about a type. Instead of using type assertions to narrow a
18
+
/// type, it's better to rely on type guards, which help avoid potential runtime errors
19
+
/// caused by unsafe type assertions.
16
20
///
17
21
/// ### Examples
18
22
///
19
23
/// Examples of **incorrect** code for this rule:
20
24
/// ```ts
21
-
/// declare const value: unknown;
22
-
///
23
-
/// const str = value as any; // unsafe type assertion
24
-
///
25
-
/// const obj = value as any as string; // double assertion through any
26
-
///
27
-
/// function processValue(input: unknown) {
28
-
/// const processed = input as any; // unsafe
29
-
/// return processed.someProperty;
25
+
/// function f() {
26
+
/// return Math.random() < 0.5 ? 42 : 'oops';
30
27
/// }
28
+
/// const z = f() as number;
29
+
///
30
+
/// const items = [1, '2', 3, '4'];
31
+
/// const number = items[0] as number;
31
32
/// ```
32
33
///
33
34
/// Examples of **correct** code for this rule:
34
35
/// ```ts
35
-
/// declare const value: unknown;
36
-
///
37
-
/// // Use specific type assertions
38
-
/// const str = value as string; // more specific assertion
39
-
///
40
-
/// // Use type guards
41
-
/// if (typeof value === 'string') {
42
-
/// const str2 = value; // safe, no assertion needed
43
-
/// }
44
-
///
45
-
/// // Use proper interface assertions
46
-
/// interface User {
47
-
/// name: string;
48
-
/// age: number;
36
+
/// function f() {
37
+
/// return Math.random() < 0.5 ? 42 : 'oops';
49
38
/// }
39
+
/// const z = f() as number | string | boolean;
50
40
///
51
-
/// const user = value as User; // specific type assertion
52
-
///
53
-
/// // Use unknown for truly unknown values
54
-
/// const unknown: unknown = value;
41
+
/// const items = [1, '2', 3, '4'];
42
+
/// const number = items[0] as number | string | undefined;
0 commit comments