TypeScript
  • Introduction
  • Introduction
    • What is TypeScript?
    • Why TypeScript?
    • Setup
  • Beginner
    • Basic types
      • Primitive types
      • Arrays and tuples
      • Enums
      • Any type
    • Objects
    • Type aliases
    • Interfaces
    • Functions
      • Function signatures
      • Void type
      • Functions as types
    • Union types
    • Type guards
    • Intersection types
    • Nullable types
    • Inference
  • Resources
    • Resources
Powered by GitBook
On this page
  • Boolean
  • Number
  • String
  • Symbol
  • Null and Undefined
  1. Beginner
  2. Basic types

Primitive types

PreviousBasic typesNextArrays and tuples

Last updated 6 years ago

In JavaScript, there are six primitive data types: boolean, number, string, symbol (new as of ES6), as well as null and undefined. TypeScript includes all of these as built-in types.

Boolean

Booleans have two logical values: true or false.

let isReady: boolean = false;
isReady = 'yes'; // Error: a string is not assignable to type 'boolean'
isReady = true; // OK

Number

All numbers in TypeScript are stored no differently than in JavaScript — as double-precision floating-point numbers.

const integer: number = 6;
const float: number = 6.66;

// Non-decimal numbers are cool too:
const hex: number = 0xf00d;
const binary: number = 0b1010;
const octal: number = 0o744;

// Let's not forget our weird friends:
const negativeZero: number = -0;
const actuallyNumber: number = NaN;
const largeNumber: number = Number.MAX_VALUE;
const pi: number = Math.PI;
const largestNumber: number = Infinity;

String

Strings work the same way as in JavaScript, where both ' and " work correctly, as well as ` for template literals.

const name: string = 'Christine';
const nameTagLabel: string = `Hello, my name is ${name}.`;

Symbol

Symbol is a unique and immutable data type introduced in ES6.

let country: symbol = Symbol('Canada'); // OK
country: symbol = 'Canada'; // Error: a string is not assignable to type 'symbol'
// typeof country === "symbol"

Null and Undefined

Both undefined and null have their own types named undefined and null, respectively.

// Not much else we can assign to these variables!
let u: undefined = undefined;
let n: null = null;

// To illustrate:
u = 200; // Error: a number is not assignable to type 'undefined'
n = 'idk'; // Error: a string is not assignable to type 'null'

By default null and undefined are subtypes of all other types, which means you can assign null and undefined to something having another type. For example:

let myNum: number = 500;
myNum = null; // OK
myNum = undefined; // also OK
IEEE 754