Understanding Basic TypeScript Types and Variables

Learn the fundamentals of TypeScript types and how to declare variables with them.

TypeScript is a strongly-typed superset of JavaScript that helps you catch errors early by using types. Understanding basic types and how to declare variables with them is the first step in writing robust TypeScript code.

In TypeScript, you can declare variables with types like `number`, `string`, and `boolean`. Declaring a type means telling TypeScript what kind of value a variable should hold. This helps prevent bugs by catching mistakes during development. For example, if you say a variable is a number, you can't accidentally assign a string to it.

typescript
let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;

// This line will cause an error:
// age = "twenty-five"; // Error: Type 'string' is not assignable to type 'number'.

In the example above, `age` is a number, `name` is a string, and `isStudent` is a boolean. If you try to assign a value of the wrong type, TypeScript will give you an error. This error means that the value you are trying to assign does not match the type you declared. To fix it, make sure you assign a value that matches the variable's type.