简体   繁体   English

如何键入 object,其键是另一种类型键的子集

[英]How to type an object whose keys are a subset of the keys of the another type

I have a type like this:我有这样的类型:

type Metadata = {
  name: string;
  size: number;
  date: string;
  language: string;
  formattedName: string;
  normalizedDate: string
};

and now I need to build this constant:现在我需要建立这个常量:

const main = {
  name: ["main", "master"],
  size: ["size"],
  date: ["date"],
  language: ["lang", "language"]
} as ??? // as Record<keyof Metadata, string[]>;

that is an object whose keys are a subset of the keys of the type Metadata and the values are an array of string.这是一个 object,其键是元数据类型键的子集,值是字符串数组。 How can I type the main object?我怎样才能输入main的object? I tried Partials(Metadata) but it seems to be not right.我试过Partials(Metadata)但它似乎不对。 Which is the right way to do that?哪个是正确的方法?

You can say that this type must "satisfy" or be at least assignable to another type, without actually overriding the inferred type information with the new satisfies keyword in 4.9+:您可以说此类型必须“满足”或至少可分配给另一种类型,而无需在 4.9+ 中使用新的satisfies关键字实际覆盖推断的类型信息:

const main = {
  name: ["main", "master"],
  size: ["size"],
  date: ["date"],
  language: ["lang", "language"]
} satisfies Partial<Record<keyof Metadata, string[]>>;

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

相关问题 如何使用特定的键子集键入对象字段的值? - How do I type the values of an object's fields with a specific subset of keys? 流:如何键入具有可变键数的对象? - Flow: How to type an object with variable number of keys? 如何使用枚举值的键定义对象类型 - How to define a type of object with keys of values of enum 如何用另一个对象的键更改对象的键 - how to change keys of object with the keys another object 如何使用 Joi 验证嵌套 object 的键应与外部对象匹配的另一个键的值为数组的键? - How to validate nested object whose keys should match with outer objects another key whose value is array using Joi? object 的子集数组基于来自另一个数组(非静态)的键,然后过滤 - Subset array of object based on keys from another array(not static) and then filter 如何从对象创建模板文字类型以具有键=值? - How to create a template literal type from object to have keys=values? Typescript - 如何使用动态对象数组中的键动态键入对象 - Typescript - How to dynamically type an object with keys from a dynamic array of objects 如何为将键动态添加到对象的函数定义返回类型? - How to define return type for a function that adds keys to an object dynamically? 如何键入返回 object 且键数和键名未知的响应? - How to type response that returns object with unknown number of keys and key names?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM