,typescript"/>

首页 > 解决方案 > 如何在记录中使文字类型可选

问题描述

基于打字稿参考

interface PageInfo {
  title: string;
}

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

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

我希望能够定义各种Record<Page, PageInfo>类似的东西:

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

在那我错误Property 'home' is missing in type '{ about: { title: string; }; contact: { title: string; }; }' but required in type 'Record<Page, PageInfo>'.

那么你将如何使它成为可能呢?

标签: typescript

解决方案


我会使用Partial,这使得一个类型的所有属性都是可选的:

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

链接到有关部分的更多信息


推荐阅读