从对象的深键创建文字类型 [英] Creating a TypeScript type from a deep key of an object

查看:0
本文介绍了从对象的深键创建文字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下对象:

数据-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

这篇关于从对象的深键创建文字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆