Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 737
Tibor Blenessy Avatar asked Dec 10 '25 02:12

Tibor Blenessy


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
like image 117
Matthew Avatar answered Dec 11 '25 16:12

Matthew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!