@@ -83,27 +83,27 @@ As a rule of thumb, explicitly declare a type when it helps narrow it.
8383</Note >
8484
8585``` ts
86- // ❌ Avoid - Don't explicitly declare a type, it can be inferred.
87- const userRole: string = ' admin' ; // Type 'string'
88- const employees = new Map <string , number >([[' Gabriel' , 32 ]]);
89- const [isActive, setIsActive] = useState <boolean >(false );
86+ // ❌ Avoid - Don't explicitly declare types when they can be inferred.
87+ const userRole: string = ' admin' ; // Inferred as wide type 'string'
88+ const employees = new Map <string , number >([[' Gabriel' , 32 ]]); // Redundant type declaration
89+ const [isActive, setIsActive] = useState <boolean >(false ); // Redundant, inferred as 'boolean'
9090
9191// ✅ Use type inference.
92- const USER_ROLE = ' admin' ; // Type 'admin'
93- const employees = new Map ([[' Gabriel' , 32 ]]); // Type 'Map<string, number>'
94- const [isActive, setIsActive] = useState (false ); // Type 'boolean'
92+ const USER_ROLE = ' admin' ; // Inferred as narrowed string literal type 'admin'
93+ const employees = new Map ([[' Gabriel' , 32 ]]); // Inferred as 'Map<string, number>'
94+ const [isActive, setIsActive] = useState (false ); // Inferred as 'boolean'
9595
96- // ❌ Avoid - Don't infer a ( wide) type, it can be narrowed.
97- const employees = new Map (); // Type 'Map<any, any>'
96+ // ❌ Avoid - Don't infer a wide types when they can be narrowed.
97+ const employees = new Map (); // Inferred as wide type 'Map<any, any>'
9898employees .set (' Lea' , 17 );
9999type UserRole = ' admin' | ' guest' ;
100- const [userRole, setUserRole] = useState (' admin' ); // Type 'string'
100+ const [userRole, setUserRole] = useState (' admin' ); // Inferred as 'string', not the desired narrowed literal type
101101
102102// ✅ Use explicit type declaration to narrow the type.
103- const employees = new Map <string , number >(); // Type 'Map<string, number>'
103+ const employees = new Map <string , number >(); // Explicitly narrowed to 'Map<string, number>'
104104employees .set (' Gabriel' , 32 );
105105type UserRole = ' admin' | ' guest' ;
106- const [userRole, setUserRole] = useState <UserRole >(' admin' ); // Type 'UserRole'
106+ const [userRole, setUserRole] = useState <UserRole >(' admin' ); // Explicit type 'UserRole'
107107```
108108
109109### Data Immutability
0 commit comments