capypad
0 day streak
typescript / beginner
Snippet

Basic Type Inference

TypeScript uses type inference to automatically determine the type of a variable based on the value assigned to it at declaration.

snippet.ts
typescript
1
2
let isActive = true;
// isActive = "yes"; // Error: Type 'string' is not assignable to type 'boolean'.
Breakdown
1
let isActive = true;
TypeScript detects the boolean value and automatically types 'isActive' as boolean.
2
// isActive = "yes";
Attempting to assign a string later results in a compiler error because the type is already fixed.