简体   繁体   English

如何在 Record 中使文字类型可选<Keys, Type>

[英]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" }
}

Link to more info on Partial 链接到有关部分的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 访问对象中的可选键,其中键是文字联合类型中的文字,没有错误“对象可能是‘未定义’” - Access optional keys in object, where key is a literal in a literal union type without error "Object is possibly 'undefined'" 如何将字符串文字类型转换为新类型的键? - How to convert a string literal type to the keys of a new type? 如何从现有类型定义类型但使用可选键(不使用 Partial)? - How to define a type from an existing type but with optional keys (not with Partial)? TypeScript 映射类型以表示具有可选 Observables 的 object(使用字符串文字映射键) - TypeScript mapped type to represent an object with optional Observables (with string literal mapped keys) 如何在打字稿中扩展记录类型的键 - How to extend the Record type's keys in typescript 如何强制映射类型具有字符串文字中的所有键 - How to enforce mapped type to have all of the keys in a string literal 如何从对象创建模板文字类型以具有键=值? - How to create a template literal type from object to have keys=values? 如何使返回类型以可选参数为条件 - How to make return type conditional on optional param 如何使 typeof typescript 中的类型可选 - How to make type optional in typeof typescript 如果存在其他类型,如何使类型可选? - How to make a type optional if other exists?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM