ThomasAribart / json-schema-to-ts

Infer TS types from JSON schemas 📝
MIT License
1.44k stars 31 forks source link

How to best surface schema descriptions as type documentation? #92

Closed erunion closed 1 year ago

erunion commented 1 year ago

As traditional types can have docblocks those can get surfaced in IDEs. How can I best surface descriptions to be available on these types?

import type { FromSchema } from 'json-schema-to-ts';

const dogSchema = {
  type: 'object',
  properties: {
    name: { type: 'string', description: "the dogs' name" },
    age: { type: 'integer' },
  },
  required: ['name', 'age'],
} as const;

type Dog = FromSchema<typeof dogSchema>;

// type Dog = {
//   /**
//    * the dogs' name
//    */
//   name: string;
//   age: number;
// };

function addDog(dog: Dog) {
  return dog;
}

addDog({ name: 'buster', age: 18 });

Traditional type on-hover:

Screen Shot 2022-10-14 at 11 43 33 AM

json-schema-to-ts on-hover:

Screen Shot 2022-10-14 at 11 43 21 AM

ThomasAribart commented 1 year ago

Hi @erunion !

I tried using some Object level JS docs but to no avail:

/**
 * @typedef {Object} Dog
 * @property {string} name - the dogs' name
 * @property {number} age - the dogs' age
 */
type Dog = FromSchema<typeof dogSchema>;

Maybe it could be solved with some better JS Doc tooling ? 🤷‍♂️

Sadly, as I much as I'd like to see such feature in json-schema-to-ts, I don't think it is possible. FromSchema only operates on types, and JS Docs are outside of that scope.

You can look at the code generator json-schema-to-typescript that does that well.

Let me know if you find anything that could work ! I'd be very interested in making this work !

ThomasAribart commented 1 year ago

Closing this issue as sadly, fixing it seems impossible :/ Cheers !

eXigentCoder commented 1 year ago
image

I also really wanted JS Doc comments, an annoying but usable workaround is to document the type manually and extend the auto generated type. It won't solve all potential issues and is more work but the docs show up. If you add more properties to the schema they will still be in the type but won't have docs until you add them. If you change the underlying type say from string to number but forget to update it in the manual type it should give you an error.

Masoodt commented 3 months ago

A simple workaround:

import type { FromSchema } from 'json-schema-to-ts';

const dogSchema = {
  type: 'object',
  properties: {
    name: { type: 'string' },
    age: { type: 'integer' },
  },
  required: ['name', 'age'],
} as const;

//Private type to extend only
type DogType = FromSchema<typeof dogSchema>;

//Main interface to use
export interface Dog extends DogType {
/**
* the dogs name
* we are using DogType auto generated type!
*/
 name:DogType['name'];

/**
* the dogs age
* 
*/
 age:DogType['age'];

}