从类型推断模块名称

Infer module name from type

假设我有以下代码:

import { createConnection } from "mysql";

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

根据 Using the Compiler API,可以使用 TypeChecker 来推断类型,例如createConnection(在本例中为“Connection”)。

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

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

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

在这种情况下 return:

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

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

你可以这样做:

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());