json-to-tstype
v1.0.0
Published
A utility library for converting JSON to TypeScript type definitions
Maintainers
Readme
json-to-tstype
一个将 JSON 数据转换为 TypeScript 类型定义的工具库,支持非标准 JSON 格式、嵌套结构和自定义类型命名。
特性
- ✅ 支持标准 JSON 和非标准 JSON(无引号键名、尾部逗号、尾部分号等)
- ✅ 智能处理嵌套对象和数组结构
- ✅ 自动生成有意义的类型名称
- ✅ 支持自定义根类型名称
- ✅ 支持使用接口代替类型别名
- ✅ 支持可选属性
- ✅ 格式化输出,可配置缩进空格数
安装
# 使用 npm
npm install json-to-tstype
# 使用 yarn
yarn add json-to-tstype
# 使用 pnpm
pnpm add json-to-tstype快速开始
import { jsonToTs } from "json-to-tstype";
// 简单示例
const json = `{
"name": "张三",
"age": 30,
"isActive": true,
"skills": ["TypeScript", "React", "Node.js"]
}`;
const typeDefinition = jsonToTs(json);
console.log(typeDefinition);输出结果:
type RootObject = {
name: string;
age: number;
isActive: boolean;
skills: SkillsArray;
};
type SkillsArray = string[];API
jsonToTs(jsonString, options?)
将 JSON 字符串转换为 TypeScript 类型定义。
参数
jsonString:string- 要转换的 JSON 字符串,支持标准和非标准格式options:JsonToTsOptions- 可选的配置选项
选项
interface JsonToTsOptions {
/**
* 根类型名称前缀,默认为 "Root"
*/
rootName?: string;
/**
* 是否格式化输出,默认为 true
*/
format?: boolean;
/**
* 缩进空格数,默认为 2
*/
indentSpaces?: number;
/**
* 是否使用接口代替类型别名,默认为 false
*/
useInterface?: boolean;
/**
* 是否将属性标记为可选,默认为 false
*/
optionalProperties?: boolean;
}示例
处理嵌套对象
const json = `{
"user": {
"profile": {
"name": "李四",
"email": "[email protected]"
},
"settings": {
"theme": "dark",
"notifications": true
}
}
}`;
const typeDefinition = jsonToTs(json);
console.log(typeDefinition);输出:
type RootObject = {
user: UserObject;
};
type UserObject = {
profile: ProfileObject;
settings: SettingsObject;
};
type ProfileObject = {
name: string;
email: string;
};
type SettingsObject = {
theme: string;
notifications: boolean;
};处理数组和混合类型
const json = `{
"users": [
{ "id": 1, "name": "张三" },
{ "id": 2, "name": "李四" }
],
"mixedData": [1, "字符串", true, { "key": "值" }]
}`;
const typeDefinition = jsonToTs(json);
console.log(typeDefinition);使用自定义选项
const json = `{
"name": "王五",
"age": 25,
"address": {
"city": "北京",
"zipCode": "100000"
}
}`;
const typeDefinition = jsonToTs(json, {
rootName: "Person", // 自定义根类型名称前缀
useInterface: true, // 使用接口代替类型别名
optionalProperties: true, // 将属性标记为可选
indentSpaces: 4, // 使用 4 个空格缩进
});
console.log(typeDefinition);输出:
interface PersonObject {
name?: string;
age?: number;
address?: AddressObject;
}
interface AddressObject {
city?: string;
zipCode?: string;
}处理非标准 JSON
const json = `{
name: "王五",
age: 25,
skills: ["编程", "设计"],
};`;
const typeDefinition = jsonToTs(json);
console.log(typeDefinition);贡献
欢迎提交问题和拉取请求!
