从对象的深键创建文字类型 [英] Creating a TypeScript type from a deep key of an object
本文介绍了从对象的深键创建文字类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下对象:
数据-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
,这将导致所有值的并集。
附注:如果您逐渐将每个路径添加到括号表示法中:)
,这可能有助于理解它这篇关于从对象的深键创建文字类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文