I'm following up on a previous question:
I have the following schema:
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: 'string',
},
},
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: 'boolean',
},
},
required: ['modified'],
additionalProperties: false,
},
},
required: ['body'],
} as const,
};
I am using FromSchema
from the json-schema-to-ts
package to infer the type of each body
attribute the const
object above.
What I need to achieve is an intersection type of POST
and PUT
bodies. The answer provided in the previous question was perfect to create a TypeScript Union
. The problem is of course that when I try to access members of body
I get an error since not all attributes will always exist on each body
.
I was even wondering if TypeScript allows us to verify that if we access one attribute from a "chosen" body
object, then it won't allow us to access the other.
I created a Playground to illustrate my question.
ANNEX