json-to-ts-cvr
v1.0.3
Published
CLI tool to convert JSON structures into TypeScript interfaces with no extra work
Maintainers
Readme
json-to-ts-cvr
A CLI tool to convert JSON structures into TypeScript interfaces or classes
Installation
# Install globally
npm install -g json-to-ts-cvr
# Or use with npx
npx json-to-ts-cvr [options]Features
- Convert JSON to TypeScript interfaces or classes
- Support for nested objects and arrays
- Generate proper type definitions (string, number, boolean, etc.)
- Auto-generate interface names from property names
- Customize interface/class names with prefixes
- Handle nullable fields
Usage
Convert JSON string to TypeScript interface
json-to-ts-cvr '{"name": "John", "age": 25}'Output:
interface Root {
name: string;
age: number;
}Convert JSON from a file and save to a TypeScript file
json-to-ts-cvr -i data.json -o types.tsGenerate TypeScript classes instead of interfaces
json-to-ts-cvr -i data.json --classOutput:
class Root {
name: string;
age: number;
constructor(data: any) {
this.name = data.name;
this.age = data.age;
}
}Add a prefix to all interface/class names
json-to-ts-cvr -i data.json --prefix IOutput:
interface IRoot {
name: string;
age: number;
}Handle null values as union types
json-to-ts-cvr -i data.json --union-nullOutput:
interface Root {
name: string;
nickname: null;
}Options
| Option | Alias | Description |
|--------|-------|-------------|
| --input <file> | -i | Input JSON file path |
| --output <file> | -o | Output TypeScript file path |
| --class | | Generate TypeScript classes instead of interfaces |
| --union-null | | Represent nullable fields as union types (field: string | null) |
| --prefix <prefix> | | Prepend a custom prefix to all interface/class names |
| --help | -h | Display help information |
| --version | -v | Display version information |
Examples
Complex nested objects
Input:
{
"user": {
"name": "John",
"address": {
"city": "New York",
"zipCode": 10001
},
"hobbies": ["reading", "gaming"]
}
}Output:
interface Root {
user: User;
}
interface User {
name: string;
address: Address;
hobbies: string[];
}
interface Address {
city: string;
zipCode: number;
}Development
# Clone the repository
git clone https://github.com/krikera/json-typescript.git
cd json-typescript
# Install dependencies
npm install
# Build the project
npm run build
# Run tests
npm testContributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Publishing
To publish to npm:
# Login to npm
npm login
# Publish package
npm publishLicense
This project is licensed under the MIT License - see the LICENSE file for details.
