简体   繁体   中英

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>'. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM