Skip to main content

One post tagged with "typing"

View All Tags

TypeScript object types with optional and minimally required properties

· 3 min read

TL;DR

// Solution 1
type LabelEntry = { label: string };
type ImageEntry = { image: string };
type Entry = LabelEntry | ImageEntry;

// Solution 2
type Entry = Record<'label' & 'image', string>;

An object type that I find myself creating very frequently is one that has one or all of several properties. For example, I can create an entry with a text label, one with an image, or one with both: