TypeScript Types
When writing code in JavaScript, you can use any kind of data without saying what type it is. TypeScript changes that by allowing (and encouraging) you to tell the computer exactly what kind of data your code expects. This helps you catch mistakes early and write more reliable programs. In this lesson, we’ll explore the basic types TypeScript gives you.
What Are Types in TypeScript?
A "type" is a way to describe what kind of value a variable can hold. For example, if a variable should store a number, you can tell TypeScript that by setting its type to number
. This means if you try to assign something else—like a string—TypeScript will give you an error.
Using types helps you understand your code better and makes it easier to catch bugs before they happen. It also improves code suggestions and documentation while coding.
Primitive Types: number, string, boolean, and any
TypeScript includes types for all the basic values you use in JavaScript:
let count: number = 5;
let username: string = "John";
let isLoggedIn: boolean = true;
There’s also a special type called any
, which lets you store any kind of value, just like regular JavaScript:
let randomValue: any = 10;
randomValue = "Now I’m a string";
Using any
can be useful when you're not sure what type a variable will be, but try to avoid it when possible so you don't miss out on TypeScript's safety features.
Arrays, Tuples, and Enums in TypeScript
Arrays can be typed to store only one kind of value:
let scores: number[] = [90, 80, 100];
let names: string[] = ["Alice", "Bob"];
Tuples are like arrays but with a fixed number of items, each with a specific type:
let user: [string, number] = ["Alice", 25];
Enums let you define a set of named values. They are great when you want to give meaning to a list of options:
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = Direction.Up;
These types give you more control over your code and help make your programs easier to understand and maintain.