Understanding Basic Types in TypeScript for Beginners
Learn the fundamental types in TypeScript and how to use them to write safer and clearer code.
TypeScript is a powerful programming language that builds on JavaScript by adding static types. These types help you catch errors early and make your code more readable. In this tutorial, we'll explore the basic types in TypeScript to get you started.
TypeScript provides several primitive types including number, string, boolean, and more. When you declare a variable with a specific type, TypeScript ensures you only use values matching that type. For example, if you declare a variable as a string, TypeScript will show an error if you try to assign a number to it.
let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;
// This will cause an error:
// age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.If you see the error 'Type 'string' is not assignable to type 'number'', it means you tried to assign a value of the wrong type to a variable. TypeScript expects a number but got a string instead. To fix this, make sure your variable is assigned a value matching its declared type. This helps prevent bugs caused by unintended value types.
Besides these basic types, TypeScript has others like any, which disables type checking (use with caution), arrays, tuples, and enums. Mastering basic types is the first step to writing strong, maintainable TypeScript code.