[英]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:我希望能够定义各种
Record<Page, PageInfo>
类似的东西:
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>'.
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:我会使用
Partial
,这使得一个类型的所有属性都是可选的:
const nav: Partial<Record<Page, PageInfo>> = {
about: { title: "about" },
contact: { title: "contact" }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.