【问题标题】:How do you use the Typescript compiler's Typechecker to get the declared (alias) type, rather than the resolved type?你如何使用 Typescript 编译器的 Typechecker 来获取声明的(别名)类型,而不是解析的类型?
【发布时间】:2017-01-14 09:14:41
【问题描述】:

我意识到这有点晦涩难懂,但也许其他人已经遇到过这个问题或者很了解 Typescript 编译器。我正在使用 Typescript 的编译器 API 处理 Typescript 文件,基于以下示例:https://github.com/Microsoft/TypeScript/wiki/Using-the-Compiler-API

想象一下我在 Typescript 中有一个这样的声明函数:

export type DateString = string;
export function parseDate(date: DateString): Date{
    let parsedDate = Date.parse(date);
    let retVal = new Date();
    retVal.setTime(parsedDate);
    return retVal;
}

在上面链接的示例中,您可以看到定义了这样的方法来提取有关符号的信息:

function serializeSymbol(symbol: ts.Symbol): DocEntry {
    return {
        name: symbol.getName(),
        type: checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration))
    };
}

当您在date: DateString 符号上运行checker.typeToString(checker.getTypeOfSymbolAtLocation(symbol, symbol.valueDeclaration) 时,它不会返回DateString,而是返回string。换句话说,你得到的不是声明的类型别名,而是完全解析的类型。就我而言,我想知道date 字段的类型是DateString。有没有一种简单的方法来查找参数的声明类型而不是其解析类型?

【问题讨论】:

    标签: typescript typescript-compiler-api


    【解决方案1】:

    不幸的是,由于“类型实习”,这不起作用。见here

    有效的方法是获取typeNode 的文本。所以基本上从节点获取文本。以下是您可能适用于您的场景的工作示例:

    // fileToAnalyze.ts
    type DateString = string;
    function myFunction(date: DateString) {
    }
    
    // main.ts
    import * as ts from "typescript";
    import * as path from "path";
    
    const program = ts.createProgram([path.join(__dirname, "fileToAnalyze.ts")], { });
    const file = program.getSourceFiles().filter(f => /fileToAnalyze/.test(f.fileName))[0];
    
    const funcNode = (file.statements[1] as ts.FunctionDeclaration);
    const parameterNode = funcNode.parameters[0];
    console.log(parameterNode.type.getText(file)); // DateString
    

    顺便说一下,你可能想看看我一直在研究的这个库 ts-type-in​​fo ts-simple-ast ts-morph如果你没见过。

    【讨论】:

    • 哇,大卫!多么棒的答案。非常感激。你的图书馆看起来很棒。是时候拿出我自己的解决方案来做这一切了。 :)
    猜你喜欢
    • 2016-10-19
    • 2021-02-21
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 2017-06-12
    相关资源
    最近更新 更多