簡體   English   中英

如何在 Record 中使文字類型可選<Keys, Type>

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM