Skip to content
On this page

Defining Schema

On this page, we will learn how to define schemas with JSDoc comments.

Description

You can describe the schema with JSDoc comments.

ts
/** Book schema Info */
interface Book {
  /** Book ID */
  id: number;
  /** Title of the book */
  title: string;
}
Generated OpenAPI Spec
yaml
components:
  schemas:
    Book:
      description: Book schema Info
      type: object
      properties:
        id:
          type: number
          description: Book ID
        title:
          type: string
          description: Title of the book
      required:
        - id
        - title

Example

If you want to add an example to the schema, you can use the @example tag.

ts
interface Book {
  /**
   * Book ID
   * @example 123456789
   * */
  id: number;
  /**
   * Title of the book
   * @example The Great Gatsby
   */
  title: string;
}
Generated OpenAPI Spec
yaml
components:
  schemas:
    Book:
      type: object
      properties:
        id:
          type: number
          description: Book ID
          example: 123456789
        title:
          type: string
          description: Title of the book
          example: The Great Gatsby
      required:
        - id
        - title

Format

If you want to specify the format of the schema, you can use the utility types provided by Tspec.

ts
import { Tspec } from 'tspec';

interface Book {
  id: Tspec.Integer;
  coverImage: Tspec.ImageUriString;
  publishedAt: Tspec.DateTimeString;
}
Generated OpenAPI Spec
yaml
components:
  schemas:
    Book:
      type: object
      properties:
        id:
          type: integer
          example: 1
        coverImage:
          format: uri
          type: string
          example: https://picsum.photos/200/300
        publishedAt:
          format: date-time
          type: string
          example: '2023-03-30T12:00:00Z'
      additionalProperties: false
      required:
      - coverImage
      - id
      - publishedAt

The following utility types are provided by Tspec.

TypeDescription
Tspec.IntegerInteger
Tspec.DateStringDate string (e.g. 2021-01-01)
Tspec.DateTimeStringDate and time string (e.g. 2021-01-01T00:00:00Z)
Tspec.PasswordStringPassword string (e.g. password)
Tspec.ByteStringByte string (e.g. dGVzdA==)
Tspec.BinaryStringBinary string (e.g. 0x1234)
Tspec.BinaryStringArrayBinary string array (e.g. [0x1234, 0x5678])
Tspec.EmailStringEmail string (e.g. test@test.com)
Tspec.UuidStringUUID string (e.g. 123e4567-e89b-12d3-a456-426614174000)
Tspec.UrlStringURL string (e.g. http://localhost)
Tspec.ImageUriStringImage URI string (e.g. https://picsum.photos/200/300)
Tspec.HostnameStringHostname string (e.g. localhost)
Tspec.Ipv4StringIPv4 string (e.g. 127.0.0.1)
Tspec.Ipv6StringIPv6 string (e.g. ::1)
Tspec.JsonPointerStringJSON Pointer string (e.g. /)