Joi to TypeScript Interface Converter

4.15.0 · active · verified Sun Apr 19

joi-to-typescript is a utility library designed to automatically generate TypeScript interfaces from Joi validation schemas. Its primary purpose is to eliminate the redundancy of manually defining both Joi schemas for runtime validation and TypeScript interfaces for compile-time type checking, adhering to the DRY (Don't Repeat Yourself) principle. The current stable version is 4.15.0, with frequent minor and patch releases addressing dependency updates and feature enhancements. It is built to work seamlessly with Joi v17.x and is particularly useful in ecosystems like Hapi.js, offering integrations with tools like `joi-to-swagger` and `hapi-swagger` by leveraging Joi's `.meta()` functionality for interface naming and structure.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates defining Joi schemas, including nested objects and unknown properties, and then using `joi-to-typescript`'s `convert` function to generate corresponding TypeScript interfaces.

import Joi from 'joi';
import { convert } from 'joi-to-typescript';

// Define your Joi schemas with .meta({ className: '...' }) for interface names
export const JobSchema = Joi.object({
  businessName: Joi.string().required(),
  jobTitle: Joi.string().required()
}).meta({ className: 'Job' });

export const WalletSchema = Joi.object({
  usd: Joi.number().required(),
  eur: Joi.number().required()
})
  .unknown() // Example with unknown keys
  .meta({ className: 'Wallet', unknownType: 'number' }); // Specify type for unknown keys

export const PersonSchema = Joi.object({
  firstName: Joi.string().required(),
  lastName: Joi.string().required().description('Last Name'),
  job: JobSchema, // Nested schema
  wallet: WalletSchema
}).meta({ className: 'Person' });

// Use the convert function to generate TypeScript interfaces
const { typescript: jobInterface } = convert(JobSchema);
const { typescript: walletInterface } = convert(WalletSchema);
const { typescript: personInterface } = convert(PersonSchema);

console.log('// Job Interface');
console.log(jobInterface);
console.log('\n// Wallet Interface');
console.log(walletInterface);
console.log('\n// Person Interface');
console.log(personInterface);

/* Expected output will resemble:
// Job Interface
export interface Job {
  businessName: string;
  jobTitle: string;
}

// Wallet Interface
export interface Wallet {
  usd: number;
  eur: number;
  [x: string]: number;
}

// Person Interface
export interface Person {
  firstName: string;
  lastName: string;
  job?: Job;
  wallet?: Wallet;
}
*/

view raw JSON →