Ts-morph: How to get the type of an import?

Created on 9 Nov 2018  路  1Comment  路  Source: dsherret/ts-morph

Given an ImportDeclaration that looks like:

import { Foo } from "./module";

Is there a way I can get the type of Foo as it is declared/exported from "./module" ?
I'd like to know if it's an InterfaceDeclaration or ClassDeclaration, etc..

question

Most helpful comment

Hey @osyrisrblx,

I've found these two ways work. There may be other ways of doing it as well.

import { Project } from "ts-simple-ast";

const project = new Project({ useVirtualFileSystem: true });
const importsFile = project.createSourceFile("imports.ts", `import { Pizza } from "./Food";`);
const pizzaClassText = "export class Pizza { }";
project.createSourceFile("Food.ts", pizzaClassText);
const foodImport = importsFile.getImportDeclarationOrThrow("./Food");
const pizzaImport = foodImport.getNamedImports()[0].getNameNode();

// option 1: get via symbol
const pizzaAliasedSymbol = pizzaImport.getSymbolOrThrow().getAliasedSymbolOrThrow();
expect(pizzaAliasedSymbol.getDeclarations().map(d => d.getText())).to.deep.equal([pizzaClassText]);

// option 2: using "go to definition"
const definitions = pizzaImport.getDefinitions();
expect(definitions.map(d => d.getNode().getParentOrThrow().getText())).to.deep.equal([pizzaClassText]);
});

>All comments

Hey @osyrisrblx,

I've found these two ways work. There may be other ways of doing it as well.

import { Project } from "ts-simple-ast";

const project = new Project({ useVirtualFileSystem: true });
const importsFile = project.createSourceFile("imports.ts", `import { Pizza } from "./Food";`);
const pizzaClassText = "export class Pizza { }";
project.createSourceFile("Food.ts", pizzaClassText);
const foodImport = importsFile.getImportDeclarationOrThrow("./Food");
const pizzaImport = foodImport.getNamedImports()[0].getNameNode();

// option 1: get via symbol
const pizzaAliasedSymbol = pizzaImport.getSymbolOrThrow().getAliasedSymbolOrThrow();
expect(pizzaAliasedSymbol.getDeclarations().map(d => d.getText())).to.deep.equal([pizzaClassText]);

// option 2: using "go to definition"
const definitions = pizzaImport.getDefinitions();
expect(definitions.map(d => d.getNode().getParentOrThrow().getText())).to.deep.equal([pizzaClassText]);
});
Was this page helpful?
0 / 5 - 0 ratings