Typescript编译器API:生成类型标识符的完整属性
给定一个类型标识符,我正在寻找一种生成对象类型AST的完整树状图的方法。 举例来说,如果我有: File1.tsTypescript编译器API:生成类型标识符的完整属性,typescript,typescript-compiler-api,Typescript,Typescript Compiler Api,给定一个类型标识符,我正在寻找一种生成对象类型AST的完整树状图的方法。 举例来说,如果我有: File1.ts type Content = { title: string, image: string, dims: number[] } type BlogPost = Pick<Content, 'title'|'image'> type User { name: string, email: string, news: Blo
type Content = {
title: string,
image: string,
dims: number[]
}
type BlogPost = Pick<Content, 'title'|'image'>
type User {
name: string,
email: string,
news: BlogPost[]
}
const test: User = { ... };
File2.ts
type Content = {
title: string,
image: string,
dims: number[]
}
type BlogPost = Pick<Content, 'title'|'image'>
type User {
name: string,
email: string,
news: BlogPost[]
}
const test: User = { ... };
我的代码必须能够从用户标识符推断出如下列表:
name
email
news.title
news.image
type Content = { title: string, id: number }
type Hello = Pick< Content, 'id' >
我通过使用checker.getTypeAtLocation进行了几项实验,逐一迭代每个属性,找到正确的符号,并尝试推断属性的名称
但我认为(希望)这种方法太难完成如此简单的事情,因为除了对象类型之外,我还必须处理属性的所有类型:Picks、Excludes、Array、ommit、KeyOf等等
我想要的只是类型的最终完整形式的属性列表
所以我的问题是:
Typescript编译器API是否提供了帮助我完成任务的工具?
举个例子,给定这样一种类型:
name
email
news.title
news.image
type Content = { title: string, id: number }
type Hello = Pick< Content, 'id' >
谢谢你的帮助
我想要的只是类型的最终完整形式的属性列表
下面是一个完整的示例,展示了如何做到这一点:
// setup
import { Project, ts } from "@ts-morph/bootstrap";
const project = new Project();
const file = project.createSourceFile("./main.ts",
`type Content = { title: string, id: number }; type Hello = Pick< Content, 'id' >`);
const typeChecker = project.createProgram().getTypeChecker();
// get type alias
const helloTypeAliasDec = file.statements.find(s => ts.isTypeAliasDeclaration(s)
&& s.name.getText(file) === "Hello")!;
// get the type alias' type
const type = typeChecker.getTypeAtLocation(helloTypeAliasDec);
// now loop over all its properties
for (const property of type.getProperties()) {
const propertyType = typeChecker.getTypeOfSymbolAtLocation(property, helloTypeAliasDec);
console.log("Name:", property.name, "Type:", typeChecker.typeToString(propertyType));
}
//设置
从“@ts morph/bootstrap”导入{Project,ts}”;
const project=新项目();
const file=project.createSourceFile(“./main.ts”,
`类型Content={title:string,id:number};类型Hello=Pick`);
const typeChecker=project.createProgram().getTypeChecker();
//获取类型别名
const helloTypeAliasDec=file.statements.find(s=>ts.IsTypeAliasDec)声明
&&getText(文件)=“你好”)!;
//获取类型别名的类型
const type=typeChecker.getTypeAtLocation(helloTypeAliasDec);
//现在循环它的所有属性
for(类型为.getProperties()的常量属性){
const propertyType=typeChecker.GetTypeOfSymbolLocation(属性,helloTypeAliasDec);
log(“Name:”,property.Name,“Type:”,typeChecker.typeToString(propertyType));
}
输出:Name:id类型:number
基于此信息,您应该能够构建AST,但您可能会遇到一些边缘情况。正是我所要寻找的,非常感谢!