【问题标题】:Infer module name from type从类型推断模块名称
【发布时间】:2022-02-12 03:34:05
【问题描述】:

假设我有以下代码:

import { createConnection } from "mysql";

const connection = createConnection({
  host: "localhost",
  user: "admin",
  database: "project",
  password: "mypassword", // sensitive
  multipleStatements: true,
});

根据Using the Compiler API,可以使用 TypeChecker 来推断例如的类型。 createConnection(在这种情况下,这将是“连接”)。

我很感兴趣的是 TypeChecker 是否可以告诉我们它获取类型的文件的模块名称(第 1 行中定义的“mysql”)。

我可以使用以下方法推断文件名:

typeProgram?.checker.getTypeAtLocation(node).type.symbol.valueDeclaration.parent.fileName

在这种情况下会返回:

"/Users/USERNAME/git/eslint-plugin-security-rules/node_modules/@types/mysql/index.d.ts"

从这里,我可以遍历文件名来获取模块名称,这是目前我解决问题的最佳解决方案。但是,我很想知道是否有我忽略的函数或变量?

【问题讨论】:

    标签: typescript types typescript-compiler-api


    【解决方案1】:

    你可以这样做:

    const symbol = checker.getTypeAtLocation(node).symbol;
    
    // "mysql".createConnection
    typeChecker.getFullyQualifiedName(symbol);
    

    或者,如果您不介意依赖内部 API:

    // "mysql"
    (symbol as any).parent?.escapedName;
    

    或者使用其他方法:

    // an actual implementation would need to be more robust than this
    const decl = symbol.getDeclarations()![0];
    const module = decl.parent.parent as ts.ModuleDeclaration;
    console.log(module.name.getText());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-06
      • 2019-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多