@@ -75,37 +75,43 @@ Being expressive and keeping types as **narrow as possible** brings benefits to
7575
7676### Type Inference
7777
78- As a rule of thumb, explicitly declare a type when it helps narrow it .
78+ As a rule of thumb, explicitly declare types when it helps to narrow them .
7979
8080<Note >
8181 Just because you don't need to add types doesn't mean you shouldn't. In some cases, explicitly declaring types can
8282 improve code readability and clarify intent.
8383</Note >
8484
85- ``` ts
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'
90-
91- // ✅ Use type inference.
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'
85+ Explicitly declare types when it helps to narrow them:
9586
96- // ❌ Avoid - Don't infer a wide types when they can be narrowed.
87+ ``` ts
88+ // ❌ Avoid
9789const employees = new Map (); // Inferred as wide type 'Map<any, any>'
9890employees .set (' Lea' , 17 );
9991type UserRole = ' admin' | ' guest' ;
10092const [userRole, setUserRole] = useState (' admin' ); // Inferred as 'string', not the desired narrowed literal type
10193
102- // ✅ Use explicit type declaration to narrow the type .
103- const employees = new Map <string , number >(); // Explicitly narrowed to 'Map<string, number>'
94+ // ✅ Use explicit type declarations to narrow the types .
95+ const employees = new Map <string , number >(); // Narrowed to 'Map<string, number>'
10496employees .set (' Gabriel' , 32 );
10597type UserRole = ' admin' | ' guest' ;
10698const [userRole, setUserRole] = useState <UserRole >(' admin' ); // Explicit type 'UserRole'
10799```
108100
101+ Don't explicitly declare types when they can be inferred:
102+
103+ ``` ts
104+ // ❌ Avoid
105+ const userRole: string = ' admin' ; // Inferred as wide type 'string'
106+ const employees = new Map <string , number >([[' Gabriel' , 32 ]]); // Redundant type declaration
107+ const [isActive, setIsActive] = useState <boolean >(false ); // Redundant, inferred as 'boolean'
108+
109+ // ✅ Use type inference.
110+ const USER_ROLE = ' admin' ; // Inferred as narrowed string literal type 'admin'
111+ const employees = new Map ([[' Gabriel' , 32 ]]); // Inferred as 'Map<string, number>'
112+ const [isActive, setIsActive] = useState (false ); // Inferred as 'boolean'
113+ ```
114+
109115### Data Immutability
110116
111117The majority of the data should be immutable, using types like ` Readonly ` and ` ReadonlyArray ` .
0 commit comments