Typescript Compiler API:生成类型标识符的完整属性树状图

Gae*_*Gac 5 typescript typescript-compiler-api

给定一个类型标识符,我正在寻找一种方法来生成对象类型 AST 的完整树状结构。举例来说,如果我有:

文件1.ts

type Content = {
    title: string,
    image: string,
    dims: number[]
}
Run Code Online (Sandbox Code Playgroud)

文件2.ts

type BlogPost = Pick<Content, 'title'|'image'>

type User {
    name: string,
    email: string,
    news: BlogPost[]
}
Run Code Online (Sandbox Code Playgroud)

文件3.ts

const test: User = { ... };
Run Code Online (Sandbox Code Playgroud)

我的代码必须能够从用户标识符推断出如下列表:

name
email
news.title
news.image
Run Code Online (Sandbox Code Playgroud)

我通过使用 进行了几项实验checker.getTypeAtLocation,逐一迭代每个属性,找到正确的符号,并尝试推断属性的名称。

但我认为(希望)这种方法对于完成如此简单的事情来说太过分了,因为除了对象类型之外,我还必须处理属性的每种可能类型:Picks、Excludes、Array、Omit、KeyOf,...

我想要的只是类型的最终完整形式的属性列表。

所以我的问题是:

Typescript 编译器 API 是否提供工具来帮助我完成任务?举例来说,给定这样一个类型:

type Content = { title: string, id: number }
type Hello = Pick< Content, 'id' >
Run Code Online (Sandbox Code Playgroud)

生成最终完整的 AST,如下所示:

type Hello = {
    id: number
}
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助

Dav*_*ret 2

我想要的只是类型的最终完整形式的属性列表。

这是一个完整的示例,展示了如何做到这一点:

// 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));
}
Run Code Online (Sandbox Code Playgroud)

输出:Name: id Type: number

根据这些信息,您应该能够构建 AST,但您可能会遇到一些边缘情况。