从对象的深键创建文字类型对象、类型、文字

2023-09-04 01:54:34 作者:楠栀

我有以下对象:

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
const schemas = {
  POST: {
    $schema: 'https://json-schema.org/draft/2019-09/schema#',
    $id: 'https://api.netbizup.com/v1/health/schema.json',
    type: 'object',
    properties: {
      body: {
        type: 'object',
        properties: {
          greeting: {
            type: 'boolean',
          },
        },
        additionalProperties: false,
      },
    },
    required: ['body'],
  } as const,
  PUT: {
    $schema: 'https://json-schema.org/draft/2019-09/schema#',
    $id: 'https://api.netbizup.com/v1/health/schema.json',
    type: 'object',
    properties: {
      body: {
        type: 'object',
        properties: {
          modified: {
            type: 'string',
          },
        },
        required: ['modified'],
        additionalProperties: false,
      },
    },
    required: ['body'],
  } as const,
};

我正在尝试创建一个从上面的对象中提取body属性类型的类型,因此如果:

有没有可以记录每个人生日的软件 记录他人生日的便签

type MyType = { body: TWhatGoesHere }

...则TWhatGoesHere等于:

{ greeting?: boolean } | { modified: string }

我正在使用json-schema-to-ts包中的FromSchema从上面的const对象推断body类型,但我无法自动&q;创建此类型。

推荐答案

您不需要实用程序类型;它就像(非常长的)括号表示法一样简单:

type SchemaBodies = (typeof schemas)[keyof typeof schemas]["properties"]["body"]["properties"];

重要的部分是keyof typeof schemas,这将导致所有值的并集。

附注:如果您逐渐将每个路径添加到括号表示法中:)

,这可能有助于理解它

Playground