{ ILoveJS }

TypeScript Types Cheatsheet

typescript

TypeScript type system reference — primitives to advanced.

7 sections · 59 items

Primitive Types

String
let name: string

Represents textual data

typescript
let greeting: string = "Hello";
Number
let count: number

Represents numeric values including integers and floats

typescript
let age: number = 25;
let price: number = 99.99;
Boolean
let flag: boolean

Represents true or false values

typescript
let isActive: boolean = true;
Null
let empty: null

Represents intentional absence of value

typescript
let data: null = null;
Undefined
let notDefined: undefined

Represents uninitialized variable

typescript
let x: undefined = undefined;
Symbol
let sym: symbol

Represents unique immutable identifier

typescript
let id: symbol = Symbol("id");
BigInt
let big: bigint

Represents arbitrary precision integers

typescript
let huge: bigint = 9007199254740991n;
Any
let anything: any

Disables type checking for the variable

typescript
let flexible: any = "string";
flexible = 42;
Unknown
let uncertain: unknown

Type-safe alternative to any requiring type narrowing

typescript
let val: unknown = getInput();
if (typeof val === "string") { val.toUpperCase(); }
Void
function log(): void

Represents absence of return value

typescript
function logMsg(msg: string): void {
  console.log(msg);
}
Never
function fail(): never

Represents values that never occur

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

Literal and Compound Types

String Literal
type Direction = "left" | "right"

Restricts value to specific string literals

typescript
type Status = "pending" | "success" | "error";
let s: Status = "pending";
Numeric Literal
type DiceRoll = 1 | 2 | 3 | 4 | 5 | 6

Restricts value to specific numbers

typescript
type Port = 80 | 443 | 8080;
let port: Port = 443;
Boolean Literal
type True = true

Restricts value to specific boolean

typescript
type AlwaysTrue = true;
let flag: AlwaysTrue = true;
Union Type
type A = TypeA | TypeB

Value can be one of several types

typescript
type StringOrNumber = string | number;
let id: StringOrNumber = "abc";
Intersection Type
type C = TypeA & TypeB

Combines multiple types into one

typescript
type Named = { name: string };
type Aged = { age: number };
type Person = Named & Aged;
Tuple Type
[Type1, Type2, ...]

Fixed-length array with specific types per position

typescript
let coord: [number, number] = [10, 20];
let entry: [string, number] = ["age", 25];
Named Tuple
[name: Type, age: Type]

Tuple with labeled elements for documentation

typescript
type Point = [x: number, y: number];
let p: Point = [5, 10];
Optional Tuple Element
[Type1, Type2?]

Tuple with optional trailing elements

typescript
type Flex = [string, number?];
let a: Flex = ["hi"];
let b: Flex = ["hi", 5];
Rest in Tuple
[Type1, ...Type2[]]

Tuple with rest elements

typescript
type StringAndNums = [string, ...number[]];
let data: StringAndNums = ["sum", 1, 2, 3];

Enums

Numeric Enum
enum Name { A, B, C }

Auto-incrementing numeric values starting from 0

typescript
enum Direction { Up, Down, Left, Right }
let dir: Direction = Direction.Up; // 0
Initialized Numeric Enum
enum Name { A = 1, B, C }

Numeric enum with custom starting value

typescript
enum Status { Pending = 1, Active, Done }
// Active = 2, Done = 3
String Enum
enum Name { A = "a", B = "b" }

Enum with string values requiring explicit initialization

typescript
enum Color { Red = "RED", Blue = "BLUE" }
let c: Color = Color.Red;
Const Enum
const enum Name { A, B }

Inlined at compile time for performance

typescript
const enum Size { S, M, L }
let size = Size.M; // compiles to: let size = 1;
Heterogeneous Enum
enum Name { A = 0, B = "b" }

Enum mixing numeric and string values

typescript
enum Mixed { No = 0, Yes = "YES" }

Interfaces and Type Aliases

Interface Declaration
interface Name { prop: Type }

Defines object shape with named contract

typescript
interface User {
  name: string;
  age: number;
}
Type Alias
type Name = { prop: Type }

Creates named alias for any type

typescript
type Point = { x: number; y: number };
type ID = string | number;
Interface Extension
interface B extends A { }

Extends existing interface with new properties

typescript
interface Animal { name: string }
interface Dog extends Animal { breed: string }
Type Intersection
type C = A & B

Combines types similar to interface extension

typescript
type Animal = { name: string };
type Dog = Animal & { breed: string };
Declaration Merging
interface A { } interface A { }

Interfaces with same name merge automatically

typescript
interface Box { height: number }
interface Box { width: number }
// Box has both properties
Optional Property
{ prop?: Type }

Property that may be undefined

typescript
interface Config {
  debug?: boolean;
  timeout?: number;
}
Readonly Property
{ readonly prop: Type }

Property that cannot be reassigned

typescript
interface Point {
  readonly x: number;
  readonly y: number;
}
Index Signature
{ [key: string]: Type }

Allows dynamic property names with consistent type

typescript
interface StringMap {
  [key: string]: string;
}
let map: StringMap = { a: "hello" };
Numeric Index Signature
{ [index: number]: Type }

Array-like index access

typescript
interface StringArray {
  [index: number]: string;
}
let arr: StringArray = ["a", "b"];

Function Types

Function Type Expression
(param: Type) => ReturnType

Defines function signature inline

typescript
type Greet = (name: string) => string;
const greet: Greet = (n) => `Hello ${n}`;
Call Signature
{ (param: Type): ReturnType }

Function type in object notation

typescript
interface SearchFunc {
  (source: string, sub: string): boolean;
}
Optional Parameter
function f(a: T, b?: U)

Parameter that can be omitted

typescript
function greet(name: string, title?: string) {
  return title ? `${title} ${name}` : name;
}
Default Parameter
function f(a: T = defaultValue)

Parameter with default value

typescript
function createUser(name: string, role = "guest") {
  return { name, role };
}
Rest Parameters
function f(...args: Type[])

Collects remaining arguments into array

typescript
function sum(...nums: number[]): number {
  return nums.reduce((a, b) => a + b, 0);
}
Function Overloads
function f(a: A): X; function f(a: B): Y;

Multiple function signatures for different inputs

typescript
function parse(input: string): number;
function parse(input: number): string;
function parse(input: any) {
  return typeof input === "string" ? parseInt(input) : String(input);
}
Method Signature
interface I { method(param: T): R }

Method declaration in interface

typescript
interface Calculator {
  add(a: number, b: number): number;
  subtract(a: number, b: number): number;
}
Construct Signature
{ new (param: T): Instance }

Describes constructor function

typescript
interface DateConstructor {
  new (value: number): Date;
}
This Parameter
function f(this: Type, ...)

Explicitly types the this context

typescript
function onClick(this: HTMLElement, e: Event) {
  this.classList.toggle("active");
}

Type Assertions and Const

As Assertion
value as Type

Asserts value is specific type

typescript
const input = document.getElementById("name") as HTMLInputElement;
input.value = "test";
Angle Bracket Assertion
<Type>value

Alternative assertion syntax not usable in JSX

typescript
const canvas = <HTMLCanvasElement>document.getElementById("c");
Non-null Assertion
value!

Asserts value is not null or undefined

typescript
function process(val: string | null) {
  console.log(val!.toUpperCase());
}
Const Assertion
value as const

Makes literal types readonly and narrowed

typescript
const colors = ["red", "green"] as const;
// type: readonly ["red", "green"]
Const Object
{ prop: value } as const

Makes all object properties readonly literals

typescript
const config = { api: "/v1", timeout: 3000 } as const;
// config.timeout is 3000, not number
Satisfies Operator
value satisfies Type

Validates type while preserving inferred type

typescript
const palette = {
  red: [255, 0, 0],
  green: "#00ff00"
} satisfies Record<string, string | number[]>;
Satisfies with Const
value as const satisfies Type

Combines const narrowing with type validation

typescript
const routes = {
  home: "/",
  about: "/about"
} as const satisfies Record<string, string>;

Type Guards

typeof Guard
typeof x === "type"

Narrows type based on JavaScript typeof

typescript
function print(val: string | number) {
  if (typeof val === "string") val.toUpperCase();
  else val.toFixed(2);
}
instanceof Guard
x instanceof Class

Narrows type based on constructor prototype

typescript
function handle(e: Error | Response) {
  if (e instanceof Error) console.log(e.message);
  else console.log(e.status);
}
In Guard
"prop" in object

Narrows based on property existence

typescript
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(a: Fish | Bird) {
  if ("swim" in a) a.swim(); else a.fly();
}
Type Predicate
function isX(a: any): a is X

Custom guard function returning type predicate

typescript
function isString(val: unknown): val is string {
  return typeof val === "string";
}
Assertion Function
function assert(x): asserts x is T

Throws if condition fails otherwise narrows type

typescript
function assertDefined<T>(val: T): asserts val is NonNullable<T> {
  if (val == null) throw new Error("Value is null");
}
Discriminated Union
type U = { kind: "a" } | { kind: "b" }

Union with common literal property for narrowing

typescript
type Shape = { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number };
function area(s: Shape) {
  return s.kind === "circle" ? Math.PI * s.r ** 2 : s.w * s.h;
}
Truthiness Narrowing
if (x) { ... }

Narrows out null undefined empty string zero

typescript
function print(s: string | null) {
  if (s) console.log(s.toUpperCase());
}
Equality Narrowing
if (x === y) { ... }

Narrows both operands to common type

typescript
function compare(a: string | number, b: string | boolean) {
  if (a === b) console.log(a.toUpperCase()); // both string
}
Array.isArray Guard
Array.isArray(x)

Narrows to array type

typescript
function process(val: string | string[]) {
  if (Array.isArray(val)) val.forEach(console.log);
  else console.log(val);
}

Related Content