gpt4 book ai didi

TypeScript 编译器 API 获取导入名称的类型

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:19 24 4
gpt4 key购买 nike

考虑以下 import 声明。

import { a } from "moduleName"

如何获取a的声明类型。例如,ClassDeclarationFunctionDeclrationNamespace 以及类或函数的类型名称?

在上面的例子中,aImportSpecifier,但是当我尝试使用 typeChecker.getSymbolAtLocationtypeChecker.getTypeAtLocation 解析它时,我只得到any 类型的 Identifier

最佳答案

您可以使用getTypeAtLocation 获取导入类型的类型,然后使用type.getSymbol().getDeclarations() 获取符号和声明.

给定以下文件:

// module.ts
export class A {
}

export function F(){
}

// sample.ts
import { A, F} from './module';

此代码将输出声明和导入的完整类型名称:

import * as ts from "typescript";

function compile(fileNames: string[], options: ts.CompilerOptions): void {
let program = ts.createProgram(fileNames, options);
let sample = program.getSourceFile("sample.ts");
let checker = program.getTypeChecker();

let list = sample.getChildAt(0) as ts.SyntaxList;
let importStm = list.getChildAt(0);
if (ts.isImportDeclaration(importStm)) { // get the declaration
let clauses = importStm.importClause;
let namedImport = clauses.getChildAt(0); // get the named imports
if (!ts.isNamedImports(namedImport)) return;
for (let i = 0, n = namedImport.elements.length; i < n; i++) { // Iterate the named imports
let imp = namedImport.elements[i];
console.log(`Import: ${imp.getText()}`);
// Get Type
let type = checker.getTypeAtLocation(imp);
// Full name
console.log(`Name: ${checker.getFullyQualifiedName(type.getSymbol())}`);
// Get the declarations (can be multiple), and print them
console.log(`Declarations: `)
type.getSymbol().getDeclarations().forEach(d => console.log(d.getText()));
}

}
}

compile(["module.ts", "sample.ts"], {});

对于接口(interface)来说,有一个复杂的问题,返回的类型是未知的,这是编译器中的注释告诉我们的有意完成的,它还建议解决方法:

// It only makes sense to get the type of a value symbol. If the result of resolving
// the alias is not a value, then it has no type. To get the type associated with a
// type symbol, call getDeclaredTypeOfSymbol.

所以对于接口(interface)我们需要使用:

let symbol = checker.getSymbolAtLocation(imp.name)
// Get Type
let type = checker.getDeclaredTypeOfSymbol(symbol);

关于TypeScript 编译器 API 获取导入名称的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50526710/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com