TypeScriptBasic types

string, number, boolean

The basic primitive types: text, numbers, and boolean values.

On this page

Example

#
TypeScript
let username: string = 'Emma'
let points: number = 120
let isPremium: boolean = false

points = points + 30
console.log(`${username}: ${points} pts, premium: ${isPremium}`)
Result
Emma: 150 pts, premium: false

Definition and usage

#

TypeScript describes values with types. The three most common are string (text), number (any number, whole or fractional), and boolean (true or false). You add a type annotation after a colon: let name: string.

The compiler makes sure a variable only ever holds a value of a matching type. Trying to assign a number to a variable typed string fails immediately, right in the editor, before the program ever runs.

Type names are written in lowercase. String, Number, and Boolean with a capital letter are JavaScript wrapper objects, and they almost never belong in a type annotation.

Syntax

#
Syntax
let name: string = "text"
let count: number = 42
let flag: boolean = true

More examples

#
An error caught by the compiler
TypeScript
let level: number = 7
level = 'seven'
// Error: Type 'string' is not assignable to type 'number'.

Good practices

#
  • When you assign a value right away, an annotation usually isn’t necessary. TypeScript infers the type on its own.
  • Write string, not String. The capitalized types are something different.

Related entries

#

Spotted a mistake or missing an example? Write to us.