Getting Started with TypeScript Variables and Data Types
Learn how to declare variables and use basic data types in TypeScript with beginner-friendly explanations and examples.
TypeScript is a powerful programming language that builds on JavaScript by adding static types. This means you can define the type of data a variable holds, which helps catch errors early and write more reliable code. In this tutorial, we'll explore how to declare variables and use common data types in TypeScript.
To declare a variable in TypeScript, you use keywords like `let`, `const`, or `var`, followed by the variable name and optionally specify the type using a colon. TypeScript supports several basic data types such as `number`, `string`, `boolean`, and more. Specifying types is optional, but it helps the compiler understand what kind of data your variables should hold.
let age: number = 25;
const name: string = 'Alice';
let isStudent: boolean = true;
// TypeScript also infers types if you don't specify them:
let score = 90; // inferred as number
// An example of a type error:
// age = 'twenty-five'; // Error: Type 'string' is not assignable to type 'number'.In the example above, we declared variables with specific types. If you try to assign a value of a different type, TypeScript will show an error. This error means you're trying to store incompatible data and can be fixed by ensuring the variable holds only data of the declared type. Using types helps you prevent bugs, improve code readability, and make development easier as your projects grow.