typescripttype-scanner
v1.0.0
Published
A simple TypeScript scanner for scanning TypeScript files.
Downloads
3
Maintainers
Readme
TypeScriptScanner
TypeScriptScanner 是一个强大的 TypeScript 代码分析工具,能够扫描并解析 TypeScript 项目中的类型定义、接口和函数。它通过解析 TypeScript 的抽象语法树 (AST),提取有关类型结构的详细信息。
主要功能
- 递归扫描目录中的所有 TypeScript 文件
- 分析接口定义的结构
- 提取类型别名的详细信息
- 解析函数签名,包括参数类型和返回类型
- 支持复杂类型的分析:
- 对象字面量类型
- 联合类型
- 交叉类型
- 字面量类型(字符串、数字、布尔值)
安装
npm install typescript-scanner基本用法
初始化扫描器
import TypeScriptScanner from 'typescript-scanner';
// 扫描单个文件或目录
const scanner = new TypeScriptScanner('./src');
// 扫描多个目录
const multiScanner = new TypeScriptScanner(['./src', './types']);扫描类型定义
// 查找并分析名为 'User' 的类型或接口
const userType = scanner.scanSpecificType('User');
console.log(JSON.stringify(userType, null, 2));分析函数类型
// 查找并分析名为 'processData' 的函数
const funcInfo = scanner.scanFunctionType('processData');
console.log(funcInfo);API 参考
构造函数
constructor(filePath?: string | string[])filePath: 可选参数,指定要扫描的文件或目录路径,可以是单个路径或路径数组
方法
scanSpecificType
scanSpecificType(name: string): KeyValuePair<string, any> | undefinedname: 要查找的类型或接口名称- 返回: 包含类型结构的 KeyValuePair 对象,如果未找到则返回 undefined
scanFunctionType
scanFunctionType(name: string): FuncRes | undefinedname: 要查找的函数名称- 返回: 包含函数详细信息的 FuncRes 对象,如果未找到则返回 undefined
返回值类型
KeyValuePair
interface KeyValuePair<K, V> {
key: K;
value: V;
}FuncRes
interface FuncRes {
funcName: string;
funcReturnType: KeyValuePair<string, any> | undefined;
funcParamsType: KeyValuePair<string, any>[];
}示例
分析接口
假设有以下 TypeScript 代码:
interface Person {
id: number;
name: string;
address: Address;
}
interface Address {
street: string;
city: string;
zipCode: number;
}使用 TypeScriptScanner 分析:
const scanner = new TypeScriptScanner('./src');
const personType = scanner.scanSpecificType('Person');
console.log(personTyp);输出结果:
{
"key": "Person",
"value": [
{
"key": "id",
"value": "number"
},
{
"key": "name",
"value": "string"
},
{
"key": "address",
"value": [
{
"key": "street",
"value": "string"
},
{
"key": "city",
"value": "string"
},
{
"key": "zipCode",
"value": "number"
}
]
}
]
}分析函数
假设有以下函数定义:
function person(address: Address): Person {
return { id: 1, name: 'John', address };
}使用 TypeScriptScanner 分析:
const funcInfo = scanner.scanFunctionType('person');
console.log(funcInfo);输出结果:
{
"funcName": "person",
"funcParamsType": [
{
"key": "address",
"value": {
"key": "Address",
"value": [
{
"key": "street",
"value": "string"
},
{
"key": "city",
"value": "string"
},
{
"key": "zipCode",
"value": "number"
}
]
}
}
],
"funcReturnType": {
"key": "Person",
"value": [
{
"key": "id",
"value": "number"
},
{
"key": "name",
"value": "string"
},
{
"key": "address",
"value": [
{
"key": "street",
"value": "string"
},
{
"key": "city",
"value": "string"
},
{
"key": "zipCode",
"value": "number"
}
]
}
]
}
}注意事项
- TypeScriptScanner 需要访问实际的 TypeScript 源文件才能进行分析
- 对于非常大的项目,初始化扫描器可能需要一些时间,因为它需要递归扫描所有 TypeScript 文件
- 该工具使用 TypeScript 编译器 API 进行分析,因此结果与 TypeScript 编译器对类型的理解一致
许可证
MIT
