Blog>
Snippets

Generating TypeScript Types from External Configuration Files

Provide an example of generating TypeScript types from JSON or YAML configuration files, integrating with TanStack Config for enhanced type safety.
npm install -g typescript json-schema-to-typescript
First, install TypeScript and json-schema-to-typescript globally using npm. This will allow us to generate TypeScript interfaces from JSON schema.
const fs = require('fs');
const path = require('path');
const { compileFromFile } = require('json-schema-to-typescript');

async function generateTypes() {
  const outputPath = path.join(__dirname, 'src/types/config.d.ts');
  // Assuming the JSON schema is named config-schema.json and is located in the src/schema directory
  const schemaPath = path.join(__dirname, 'src/schema/config-schema.json');

  compileFromFile(schemaPath)
    .then(ts => fs.writeFileSync(outputPath, ts))
    .catch(error => console.error('Failed to generate types:', error));
}

generateTypes();
This script reads a JSON schema from a file, and then uses json-schema-to-typescript to generate TypeScript definitions from that schema. The generated type definitions are saved to a designated file. This allows us to have type safety based on our configuration schema.
import { defineConfig } from 'tanstack-config';
import { MyConfigType } from './types/config';

const config = defineConfig<MyConfigType>({ /* configuration values here */ });

export default config;
Finally, this snippet demonstrates how to use the generated TypeScript types with TanStack Config. 'MyConfigType' is the interface imported from the generated types file. This ensures that the configuration adheres to the structure and types defined in the JSON schema, enhancing type safety.