【问题标题】:Typescript Compiler API: Generate the full properties arborescence of a Type IdentifierTypescript Compiler API:生成类型标识符的完整属性树状结构
【发布时间】:2020-05-31 14:35:10
【问题描述】:

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

File1.ts

type Content = {
    title: string,
    image: string,
    dims: number[]
}

File2.ts

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

type User {
    name: string,
    email: string,
    news: BlogPost[]
}

File3.ts

const test: User = { ... };

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

name
email
news.title
news.image

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

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

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

所以我的问题是:

Typescript Compiler API 是否提供工具来帮助我完成任务? 例如,给定一个像这样的类型:

type Content = { title: string, id: number }
type Hello = Pick< Content, 'id' >

像这样生成一个最终且完整的 AST:

type Hello = {
    id: number
}

感谢您的帮助

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

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

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

    // 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));
    }
    

    输出:Name: id Type: number

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

    【讨论】:

    • 正是我想要的,非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-02
    • 2022-01-09
    相关资源
    最近更新 更多