The Three Basic Types

string, number, and boolean

7 min read

Meet the big three

Almost everything on a website boils down to three kinds of simple values. TypeScript has a type name for each:

  • string for text, like a username or a page title
  • number for any number, whole or decimal
  • boolean for exactly two values: true or false

To attach a type to a variable, you write a colon and the type name after the variable name. This is called a type annotation:

let username: string = 'gwen';
let cartTotal: number = 24.5;
let isLoggedIn: boolean = false;

Read the first line out loud as: username is a string, and right now it holds 'gwen'. The annotation is a promise. From now on, username may only ever hold strings.

What breaking the promise looks like

Try to put the wrong kind of value in, and TypeScript speaks up immediately:

let cartTotal: number = 24.5;
cartTotal = 'twenty four';

The error reads: Type 'string' is not assignable to type 'number'. Error messages in TypeScript usually follow this shape: the type you gave, then the type that was expected. Once you learn to read them that way, they stop feeling scary and start feeling like helpful directions.

One number type to rule them all

Some languages split numbers into integers, floats, and more. TypeScript keeps it simple: 42, 3.14, and -7 are all just number. There is no separate decimal type to worry about.

Booleans keep decisions honest

Booleans shine in conditions. Suppose you track whether a user has verified their email:

let isVerified: boolean = true;

if (isVerified) {
  showDashboard();
}

Because isVerified is typed as boolean, nobody can accidentally assign it the string 'yes' or the number 1 somewhere else in the project. On a big codebase, that kind of quiet guarantee saves real debugging hours.

Watch the case: the type names are all lowercase: string, number, boolean. TypeScript also has capitalized versions like String, but those mean something different and you should not use them for annotations. Lowercase, always.

Quick check

Q1 Which type annotation is correct for a variable that holds true or false?

Q2 A variable is declared as let age: number = 30. What happens if you later write age = 'thirty'?

Want to save your progress? It's free.

Create a free account