Home > Back-end >  Creating a TypeScript type from a deep key of an object
Creating a TypeScript type from a deep key of an object

Time:03-08

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.

CodePudding user response:

You don't need a utility type; it's as simple as (very long) bracket notation:

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

The important part is keyof typeof schemas, which results in a union of all the values.

P. S. It might help to understand it if you gradually add each path in the bracket notation :)

Playground

  • Related