Skip to content

TypeScript Objects

const activeGlobalFilters = typeToFilter[
    globalFilter
] as typeof filterOptions[keyof typeof filterOptions];

Object that has at least these two properties

<T extends {first: string; last: string}>(obj: T)
/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};
/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};

Extend a type

interface LoadingWidgets {
    [widgetId?: number]: boolean;
}

interface IsLoading {
    widgets: LoadingWidgets;
    [key?: string]: boolean | LoadingWidgets;
}

Avoid optional properties

  • Explicitly model which combinations exist and which don't
interface Product {
    id: string;
    type: "digital" | "physical";
    weightInKg?: number;
    sizeInMb?: number;
}
interface Product {
    id: string;
    type: "digital" | "physical";
}

interface DigitalProduct extends Product {
    type: "digital";
    sizeInMb: number;
}

interface PhysicalProduct extends Product {
    type: "physical";
    weightInKg: number;
}

Record

Restrict what the key and the value can be - restrict the keys (string union) - restrict the values

type User = {
    name: string;
    email: string;
};
type Country = "uk" | "france" | "india";

const myData: Record<Country, User> = {
    uk: { name: "John", email: "a@a.a" },
    france: { name: "Sarah", email: "a@a.a" },
    india: { name: "Jane", email: "a@a.a" },
};

Empty object

type PropertyKey = string | number | symbol
const a: Record<PropertyKey, never> = {}

Record: object of string -> string

Record<string, string>;

object type vs UnknownObject

interface UnknownObject {
    [key: string]: unknown;
}

type UnknownObject = Record<string, unknown>;

object will match functions too!

thisIsValid.ts
const a: object = () => {};
(a: object) => a.something  // error

(a: UnknownObject) => a.something // unknown

Narrowing which props are accepted for subtypes

There is something

Enums

May be fixed in TypeScript 5.0?

How to iterate over string union

const names = ["Bill Gates", "Steve Jobs", "Linus Torvalds"] as const;
type Names = typeof names[number];

Last update: 2023-04-24