TypeScript Basic Types - string, number, boolean, null, undefined, void, never, any, unknown

Master all TypeScript basic types: string, number, boolean, null, undefined, void, never, any, unknown, and more!

Introduction

Let's cover all TypeScript basic types in depth!

What You Will Learn

  • string, number, boolean
  • null, undefined
  • void, never
  • any vs unknown
  • bigint, symbol

Prerequisites

Primitive Types

1. string

let color: string = "blue";
color = 'red';
color = `The color is ${color}`;

2. number

let decimal: number = 6;
let float: number = 3.14;
let hex: number = 0xf00d;
let binary: number = 0b1010;

3. boolean

let isDone: boolean = false;

4. null & undefined

let u: undefined = undefined;
let n: null = null;

5. void

Used when a function returns nothing!

function log(message: string): void {
  console.log(message);
}

6. never

Represents values that never occur! Like a function that always throws an error!

function throwError(message: string): never {
  throw new Error(message);
}

7. any

Escape hatch - turns off type checking! Try to avoid!

let value: any = "Hello";
value = 42;
value = true;

8. unknown

Safe alternative to any!

let value: unknown = "Hello";
if (typeof value === "string") {
  console.log(value.toUpperCase());
}

9. bigint (ES2020+)

let big: bigint = 100n;

10. symbol

let sym1 = Symbol();
let sym2 = Symbol("key");

any vs unknown

| Feature | any | unknown | |---------|-----|---------| | Assignable to anything | Yes | No | | Anything assignable to it | Yes | Yes | | Safe? | No | Yes! |

Always prefer unknown over any!

Best Practices

  1. Avoid any: Use unknown instead!
  2. Use type inference: Let TS do the work!
  3. Be explicit when needed: When inference isn't enough!

Summary

All TypeScript basic types!

Related Articles

Previous Tutorial

Variables & Type Annotations

Next Tutorial

Let's learn functions! → TypeScript Functions