Sergino
Sergino

Reputation: 10818

How to make literal type optional in Record<Keys, Type>

Based on typescript reference:

interface PageInfo {
  title: string;
}

type Page = "home" | "about" | "contact";

const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" },
};

I want to be able to define various Record<Page, PageInfo> something like that:

const nav: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" }
};

In that I Error Property 'home' is missing in type '{ about: { title: string; }; contact: { title: string; }; }' but required in type 'Record<Page, PageInfo>'.

So how would you make it possible?

Upvotes: 1

Views: 1340

Answers (1)

Nicholas Tower
Nicholas Tower

Reputation: 84912

I would use Partial, which makes all properties of a type optional:

const nav: Partial<Record<Page, PageInfo>> = {
  about: { title: "about" },
  contact: { title: "contact" }
}

Link to more info on Partial

Upvotes: 6

Related Questions