TypeScript Compiler API: How to get fully qualified name of type without absolute path?

Viewed 460

I am trying to create a tool working on specific types using TypeScript's TypeChecker API. I need to uniquely identify specific types - like Angular's DomSanitizer from @angular/platform-browser package. I have following code to get fully qualified name of the type

let type = typeChecker.getTypeAtLocation(node);
let fqn = typeChecker.getFullyQualifiedName(type.getSymbol());

However, this returns name which contains absolute path to the node_modules directory, such as "/home/user/project/node_modules/@angular/platform-browser/platform-browser".DomSanitizer

I would like to remove the part which is project specific, to have only something like @angular/plaform-browser/platform-browser.DomSanitizer . I would prefer to use TypeScript API rather than doing some string operations on this value, as I expect the API to be more robust.

1 Answers

If you know what the project root is, you can use NodeJS's path.relative method for this:

import * as path from 'path'

const type = typeChecker.getTypeAtLocation(node);
const fqn = typeChecker.getFullyQualifiedName(type.getSymbol());

const projectRoot = '/home/user/project/node_modules/'
const relativePath = path.relative(projectRoot, fqn)
console.log(relativePath) // should print @angular/plaform-browser/platform-browser.DomSanitizer
Related