Understanding TypeScript Data Types and Variables
A beginner-friendly guide to TypeScript data types and variables with examples and error explanations.
TypeScript is a powerful language that builds on JavaScript by adding static types. This means you can define the kind of data a variable can hold, which helps catch errors early and makes your code easier to understand. In this tutorial, we'll learn about the basic data types and how to declare variables in TypeScript.
In TypeScript, you can specify types for variables like numbers, strings, booleans, arrays, and more. When you assign a value that doesn't match the specified type, TypeScript will give you an error, helping prevent bugs before running your code.
let age: number = 25;
let userName: string = "Alice";
let isLoggedIn: boolean = true;
// An array of numbers
let scores: number[] = [90, 85, 100];
// This will cause an error
// age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.If you see an error like "Type 'string' is not assignable to type 'number'", it means you're trying to store a value in a variable of the wrong type. For example, assigning a string to a variable declared as a number. To fix this, make sure the value's type matches the variable’s type declaration.