'Creating a TypeScript type from a deep key of an object
I have the following object:
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,
};
I'm trying to create a type that would extract the body property type from the above object, so if:
type MyType = { body: TWhatGoesHere }
...then TWhatGoesHere would be equal to:
{ greeting?: boolean } | { modified: string }
I am using FromSchema from the json-schema-to-ts package to infer the body type from the const object above, but I'm unable to "automatically" create this type.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
