TypeScript BasicsCore· 30 min read

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:

TypeHoldsExample value
stringText'hello', "Asha"
numberAny number (int or decimal)42, 3.14
booleantrue or falsetrue
arrayA list of one type[1, 2, 3]

A worked example

Here is a little profile, each variable clearly typed:

Three basic types in action
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:

Two ways to type an array
// "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

Pushing the wrong 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"]?

Answer: It is a list (array) of text values, so the type is string[] — equivalently Array<string>.

✍️ Practice

  1. Declare a typed price: number, title: string and inStock: boolean for a product.
  2. Make a tags: string[] array, push a valid tag, then try pushing a number and read the error.

🏠 Homework

  1. Write five typed variables describing a movie (title, year, rating, isWatched, genres list) using all four basic types.
Want to learn this with a mentor?

CodingClave runs guided, project-based training (28-day, 45-day & 6-month batches).

Explore Training →