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>'.
那么你将如何使它成为可能呢?
解决方案
我会使用Partial
,这使得一个类型的所有属性都是可选的:
const nav: Partial<Record<Page, PageInfo>> = {
about: { title: "about" },
contact: { title: "contact" }
}
推荐阅读
- python-3.x - 解决 re.compile 掩码/密码的问题
- javascript - jquery:如何检查是否设置了事件
- string - 我编写了一个函数来将字符串分成由 $ 分隔的部分现在我需要使用 select from 来访问它,但出现错误
- javascript - 当数据库中没有数据时,Select2 AJAX 不显示“未找到数据”,而是显示搜索参数作为选择选项
- sql - 优化 postgresql 查询
- c++ - WinUsb with C++ Builder 10.3 社区版
- html - 没有从 soup.findAll() 获得所有结果
- amp-html - 带有 amp-auto-ads 的 Adsense 覆盖广告?
- google-cloud-dataflow - 当新数据到达 Bigquery 时触发数据流作业
- sql - 如何使用最右边的表过滤多对多左连接?