API del compilador de TypeScript para obtener el tipo de los nombres importados
Considere la siguiente declaración import.
import { a } from "moduleName"
¿Cómo puedo obtener el tipo declarado de a? Por ejemplo, DeclaraciónDeClase o DeclaraciónDeFunción o EspacioDeNombres y también el nombre del tipo en el caso de una clase o función?
En el ejemplo anterior, a es ImportSpecifier, sin embargo, cuando intento resolverlo usando typeChecker.getSymbolAtLocation y typeChecker.getTypeAtLocation solo obtengo un Identifier de tipo any.
Respuesta #1
Puedes usar getTypeAtLocation para obtener el tipo del tipo de la importación, y luego usar type.getSymbol().getDeclarations() para obtener el símbolo y las declaraciones.
Dado los siguientes archivos:
// module.ts
export class A {
}
export function F(){
}
// sample.ts
import { A, F} from './module';
Este código mostrará las declaraciones y el nombre completo del tipo para las importaciones:
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"], {});
Para las interfaces hay una complicación, el tipo devuelto es desconocido, esto se hace intencionalmente como nos indica este comentario en el compilador, y también sugiere una solución alternativa:
// 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.
Entonces, para las interfaces necesitamos usar:
let symbol = checker.getSymbolAtLocation(imp.name)
// Get Type
let type = checker.getDeclaredTypeOfSymbol(symbol);
