Basic Types: string, number, boolean, array
Label your values with the four everyday types and let TypeScript guard them.
What you will learn
- Annotate variables with string, number and boolean
- Type arrays two different ways
- See what happens when a value breaks its type
The everyday types
You add a type to a variable by writing a colon and the type name after its name: let age: number. These are the four you will use constantly:
| Type | Holds | Example value |
|---|---|---|
string | Text | 'hello', "Asha" |
number | Any number (int or decimal) | 42, 3.14 |
boolean | true or false | true |
array | A list of one type | [1, 2, 3] |
A worked example
Here is a little profile, each variable clearly typed:
let username: string = 'asha_codes';
let age: number = 21;
let isStudent: boolean = true;
console.log(username, age, isStudent);Note: Output:
asha_codes 21 true
Each variable now has a fixed type. If you later wrote age = 'old', TypeScript would flag it immediately.
Typing arrays
An array holds many values of the same type. There are two ways to write it; both mean exactly the same thing:
// "list of numbers" — two equivalent styles
let scores: number[] = [90, 85, 100];
let names: Array<string> = ['Asha', 'Ben'];
scores.push(95); // fine — 95 is a number
console.log(scores);Note: Output:
[ 90, 85, 100, 95 ]
number[] and Array<number> mean the same thing. Pushing a number is allowed; pushing a string would be an error.
When a value breaks its type
let scores: number[] = [90, 85, 100];
scores.push('A+'); // mistake: that is a string!Note: Output: Error: Argument of type 'string' is not assignable to parameter of type 'number'. The array was declared as numbers only, so a string is rejected — the bug is caught before it can spread.
Tip: Read the colon as "is a". age: number means "age is a number". Read number[] as "an array of numbers".
Watch out: Coming from other languages you might expect int and float. TypeScript has just one number type that covers both 42 and 3.14 — the same as JavaScript. Likewise the type names are lowercase: write string, not String (the capitalised String is something different and best avoided).
Q. Which type would you use for a list of usernames like ["asha", "ben"]?
✍️ Practice
- Declare a typed
price: number,title: stringandinStock: booleanfor a product. - Make a
tags: string[]array, push a valid tag, then try pushing a number and read the error.
🏠 Homework
- Write five typed variables describing a movie (title, year, rating, isWatched, genres list) using all four basic types.