Basic Types in TypeScript Explained with Examples
Learn the fundamental data types in TypeScript with clear examples for beginners.
TypeScript is a typed superset of JavaScript that adds static types. Understanding the basic types is essential for writing safe and reliable TypeScript code. These types help you catch errors early and provide better autocompletion in editors.
Here are the most common basic types you will use in TypeScript: number, string, boolean, array, tuple, enum, any, void, null, and undefined. Let's go through some of them with simple examples.
let isDone: boolean = false;
let age: number = 25;
let userName: string = 'Alice';
let hobbies: string[] = ['Reading', 'Gaming'];
// Tuple allows you to express an array with fixed number of elements of specific types
let address: [string, number] = ['Main Street', 123];
// Enum helps to define a set of named constants
enum Color {
Red,
Green,
Blue
}
let favoriteColor: Color = Color.Green;If you assign a value of the wrong type, TypeScript will give you an error. For example, if you try to assign a number to a string variable, you'll see an error message. This happens because TypeScript expects the value to match the declared type. To fix it, make sure you assign the correct type as declared.