TypeScriptBasic types
string, number, boolean
The basic primitive types: text, numbers, and boolean values.
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 = trueMore examples
#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, notString. The capitalized types are something different.
Related entries
#- Type inferenceThe compiler figuring out types automatically, without you writing annotations.
- Literal typesTypes that allow only specific values, e.g. "easy" | "hard".
- Arrays: number[] and Array<T>Array types, where every element has the same type.
- anyThe type that turns off checking: the value can be anything.
Spotted a mistake or missing an example? Write to us.