
本文深入探讨如何利用typescript编译器api,将typescript文件中导出的常量对象的推断类型结构,以编程方式转换为json格式的类型模式表示。我们将详细讲解如何解析抽象语法树(ast)、获取精确的类型信息,并递归构建所需的类型描述json,从而实现对类型而非运行时值的结构化表示。
在TypeScript开发中,我们经常会遇到需要将代码中定义的类型结构,以某种标准化的数据格式(例如JSON)进行表示或传输的场景。这不同于简单地将一个JavaScript对象的运行时值转换为JSON字符串。用户期望的是一个反映类型名称(如"string"、"number")的JSON结构,而非实际的字面量值。要实现这一目标,我们需要借助TypeScript编译器API来深入解析源代码,提取其类型元数据。
考虑以下TypeScript文件 my-ts-file.ts:
// my-ts-file.ts
const inner = {
hello: "world",
};
export const value = {
prop1: "hello",
prop2: "world",
prop3: 42,
prop4: inner,
};当TypeScript编译器处理这段代码时,它会为 value 变量推断出如下类型:
const value: {
prop1: string;
prop2: string;
prop3: number;
prop4: {
hello: string;
};
}用户希望得到的是一个JSON结构,其中每个属性的值是其对应的TypeScript类型名称,例如:
{
"prop1": "string",
"prop2": "string",
"prop3": "number",
"prop4": {
"hello": "string"
}
}简单地使用 JSON.parse(JSON.stringify(value)) 只能将 value 的运行时值转换为JSON,其结果将是:
{
"prop1": "hello",
"prop2": "world",
"prop3": 42,
"prop4": {
"hello": "world"
}
}这显然不符合将“推断类型”转换为JSON模式的需求。因此,我们需要一个能够访问和解释TypeScript类型系统的工具,即TypeScript编译器API。
TypeScript编译器API提供了一套强大的接口,允许我们以编程方式与TypeScript代码进行交互。它能够解析源代码文件,构建抽象语法树(AST),并执行类型检查,从而获取到变量、函数、类等的详细类型信息。
实现将推断类型转换为JSON模式的关键步骤如下:
首先,确保你的项目中安装了 typescript 包:
npm install typescript
接下来,我们将创建一个Node.js脚本(例如 type-extractor.ts)来实现上述逻辑。
1. 目标TypeScript文件 (my-ts-file.ts)
// my-ts-file.ts
const inner = {
hello: "world",
};
export const value = {
prop1: "hello",
prop2: "world",
prop3: 42,
prop4: inner,
};
export const anotherValue = {
items: [1, 2, 3],
status: "active",
};2. 类型提取脚本 (type-extractor.ts)
import * as ts from 'typescript';
import * as path from 'path';
/**
* 将TypeScript类型对象转换为其对应的字符串名称。
* @param typeChecker TypeScript类型检查器实例。
* @param type TypeScript类型对象。
* @returns 类型的字符串表示(如 "string", "number", "boolean", "object", "array")。
*/
function getTypeString(typeChecker: ts.TypeChecker, type: ts.Type): string {
if (type.flags & ts.TypeFlags.String) {
return "string";
}
if (type.flags & ts.TypeFlags.Number) {
return "number";
}
if (type.flags & ts.TypeFlags.Boolean) {
return "boolean";
}
if (type.flags & ts.TypeFlags.Null) {
return "null";
}
if (type.flags & ts.TypeFlags.Undefined) {
return "undefined";
}
if (type.flags & ts.TypeFlags.Any) {
return "any";
}
if (type.flags & ts.TypeFlags.Void) {
return "void";
}
if (type.flags & ts.TypeFlags.Unknown) {
return "unknown";
}
if (type.flags & ts.TypeFlags.BigInt) {
return "bigint";
}
if (type.flags & ts.TypeFlags.ESSymbol) {
return "symbol";
}
// 检查是否为数组类型
if (typeChecker.isArrayLikeType(type)) {
const elementType = typeChecker.getTypeArguments(type as ts.TypeReference)[0];
if (elementType) {
return getTypeString(typeChecker, elementType) + "[]";
}
return "any[]"; // 无法确定元素类型
}
// 检查是否为对象类型(包括字面量对象和接口)
if (type.flags & ts.TypeFlags.Object || typeChecker.getPropertiesOfType(type).length > 0) {
return "object";
}
// 默认返回类型文本,这对于更复杂的类型(如联合类型、字面量类型)可能更精确
return typeChecker.typeToString(type);
}
/**
* 递归地将TypeScript类型转换为JSON模式表示。
* @param typeChecker TypeScript类型检查器实例。
* @param type TypeScript类型对象。
* @returns 对应的JSON模式对象。
*/
function convertTypeToJsonSchema(typeChecker: ts.TypeChecker, type: ts.Type): any {
// 检查是否为原始类型
const primitiveType = getTypeString(typeChecker, type);
if (primitiveType !== "object" && !primitiveType.endsWith("[]")) {
return primitiveType;
}
// 检查是否为数组类型
if (typeChecker.isArrayLikeType(type)) {
const elementType = typeChecker.getTypeArguments(type as ts.TypeReference)[0];
return [elementType ? convertTypeToJsonSchema(typeChecker, elementType) : "any"];
}
// 处理对象类型
const properties: { [key: string]: any } = {};
const symbol = type.getSymbol();
if (symbol && symbol.declarations && symbol.declarations.length > 0) {
// 尝试从声明中获取属性(例如接口或类型别名)
const declaration = symbol.declarations[0];
if (ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration)) {
typeChecker.getPropertiesOfType(type).forEach(prop => {
const propType = typeChecker.getTypeOfSymbolAtLocation(prop, declaration);
properties[prop.getName()] = convertTypeToJsonSchema(typeChecker, propType);
});
return properties;
}
}
// 对于匿名对象字面量,直接获取其属性
typeChecker.getPropertiesOfType(type).forEach(prop => {
const propType = typeChecker.getTypeOfSymbolAtLocation(prop, prop.valueDeclaration || prop.declarations[0]);
properties[prop.getName()] = convertTypeToJsonSchema(typeChecker, propType);
});
return properties;
}
/**
* 提取指定文件中导出变量的类型并转换为JSON模式。
* @param filePath 目标TypeScript文件的路径。
* @param variableName 目标导出变量的名称。
* @returns 包含类型模式的JSON对象,如果未找到则为null。
*/
function extractExportedVariableTypeAsJson(filePath: string, variableName: string): any | null {
const program = ts.createProgram([filePath], {
target: ts.ScriptTarget.ESNext,
module: ts.ModuleKind.CommonJS,
strict: true,
// 如果你的项目有tsconfig.json,可以这样加载
// project: path.dirname(filePath)
});
const sourceFile = program.getSourceFile(filePath);
if (!sourceFile) {
console.error(`Error: Could not find source file at ${filePath}`);
return null;
}
const typeChecker = program.getTypeChecker();
let result: any | null = null;
ts.forEachChild(sourceFile, node => {
// 查找 `export const variableName = ...`
if (ts.isVariableStatement(node) && node.modifiers &&
node.modifiers.some(m => m.kind === ts.SyntaxKind.ExportKeyword)) {
node.declarationList.declarations.forEach(declaration => {
if (ts.isIdentifier(declaration.name) && declaration.name.text === variableName) {
const symbol = typeChecker.getSymbolAtLocation(declaration.name);
if (symbol) {
const type = typeChecker.getTypeOfSymbolAtLocation(symbol, declaration.name);
result = convertTypeToJsonSchema(typeChecker, type);
}
}
});
}
});
return result;
}
// 示例用法
const tsFilePath = path.join(__dirname, 'my-ts-file.ts');
const valueTypeJson = extractExportedVariableTypeAsJson(tsFilePath, 'value');
if (valueTypeJson) {
console.log(`Type schema for 'value':\n${JSON.stringify(valueTypeJson, null, 2)}`);
}
const anotherValueTypeJson = extractExportedVariableTypeAsJson(tsFilePath, 'anotherValue');
if (anotherValueTypeJson) {
console.log(`\nType schema for 'anotherValue':\n${JSON.stringify(anotherValueTypeJson, null, 2)}`);
}运行结果:
Type schema for 'value':
{
"prop1": "string",
"prop2": "string",
"prop3": "number",
"prop4": {
"hello": "string"
}
}
Type schema for 'anotherValue':
{
"items": [
"number"
],
"status": "string"
}extractExportedVariableTypeAsJson 函数:
convertTypeToJsonSchema 函数:
getTypeString 函数:
通过TypeScript编译器API,我们可以深入到源代码的抽象语法树和类型系统中,以编程方式提取并分析类型信息。本文详细介绍了如何加载TypeScript文件、获取类型检查器、定位目标变量并递归地将其推断类型转换为自定义的JSON模式表示。理解并掌握这一过程,对于构建代码分析工具、类型文档生成器或动态表单生成器等场景具有重要的意义。虽然处理所有复杂的TypeScript类型需要更精细的逻辑,但本文提供的基础框架为进一步的扩展和定制奠定了坚实的基础。
以上就是将TypeScript推断类型转换为JSON模式表示的编程指南的详细内容,更多请关注php中文网其它相关文章!
编程怎么学习?编程怎么入门?编程在哪学?编程怎么学才快?不用担心,这里为大家提供了编程速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号