![](/img/trans.png)
[英]Access optional keys in object, where key is a literal in a literal union type without error "Object is possibly 'undefined'"
[英]How to make literal type optional in Record<Keys, Type>
基於打字稿參考:
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>'.
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" }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.