Isaac.

Types in TypeScript

In TypeScript, types are a way to describe the shape of a value, telling us what kind of data it holds. This helps catch errors during development, making your code more robust and easier to maintain. TypeScript offers a rich set of built-in types, and you can also create your own.

Primitive Types

These are the most basic types of data.

string

let message: string = "Hello, TypeScript!";

number

let age: number = 30;
let price: number = 19.99;

boolean

let isDone: boolean = false;

null

let currentName: string | null = null;

undefined

let undeclaredVariable: undefined;

symbol

const id = Symbol('user_id');
let userId: symbol = id;

bigint

let veryLargeNumber: bigint = 123456789012345678901234567890n;

Object Types

These represent more complex data structures.

any

let dynamicValue: any = 42;
dynamicValue = "Now I'm a string!"; 

object

let userObject: object = { name: "Alice", age: 25 };

Special Types

void

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

never

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

Union and Intersection Types

Union Types (|)

let status: "pending" | "success" | "error" = "pending";
status = "success"; 

Intersection Types (&)

interface Draggable {
  drag(): void;
}
interface Resizable {
  resize(): void;
}

type UIWidget = Draggable & Resizable;

let textBox: UIWidget = {
  drag: () => { },
  resize: () => { }
};

Type Inference

TypeScript has a powerful feature called type inference. If you do not explicitly provide a type annotation, TypeScript will try to infer the type based on the value assigned.

let greeting = "Hello"; 

Understanding these types is fundamental to writing effective TypeScript code. You can combine them to create complex and type-safe applications.