Discover the origin file of a type with the TypeScript compiler API

Is there a way to determine the file where a specific type was defined given a ts.Program and the name of the type? The type will always exist in the program and be exported from the main entry point.

I am looking for guidance on which APIs to use or an example similar to what I described. One potential starting point could involve using program.getTypeChecker() to obtain a ts.TypeChecker, but none of its methods seem to offer a direct solution to map from a type name to its origin.

(While VS Code's "go to definition" feature is somewhat comparable, it operates through multiple layers of abstraction and does not provide a helpful demonstration in this context.)

Answer №1

By leveraging a given type, you have the ability to access its symbol and from there, navigate to the declarations associated with that symbol. It's worth noting that a type might be linked to multiple declarations due to declaration merging, which could potentially be located in different source files.

If you're interested, here is some sample code (not tested, but should function as intended):

const symbol = type.getSymbol()!; // note: consider handling for cases where it's undefined
const declarations = type.declarations;
const sourceFiles = Array.from(new HashSet(declarations.map(d => d.getSourceFile()));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Is there a way to generate a Date Object without including the time component while utilizing the format YYYY-MM-DD within

I'm struggling to generate a Date object with just the date when using 'YYYY-MM-DD' input format. Here's the code I'm using: let date1 = new Date('2022-01-06') let date2 = new Date('01/06/2022') The results ar ...

Enriching React components with dynamic key-value elements

Is there a way to dynamically add an event key to a button in React? interface ButtonProps{ eventType: string, eventCallback: any } const Button = (props: ButtonProps)=>{ return ( <button {props.eventType}={props.eventCallback}> ...

Conditional void parameter type in Typescript

Attempting to create a custom Error class that can handle different data based on the error code seemed like a complex task for TypeScript. However, surprisingly, it was successful: const enum ERROR_CODES { E_AUTHORIZATION = 'Authorization error&ap ...

Potential absence of object.ts(2531)

Currently, I am working on a project using Node.js with Typescript. My task involves finding a specific MongoDB document, updating certain values within it, and then saving the changes made. However, when I try to save the updated document, an error is bei ...

Troubleshooting: Solving the issue of the exhaustMap operator in HTTP request only being executed once

One of my challenges is dealing with multiple button clicks that trigger HTTP requests and receive data from the server. I'm looking for a way to prevent users from clicking the button again until the previous request is complete. I found a solution ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

What is the best way to design functions that can return a combination of explicit types and implicit types?

When looking at the code provided below, function system(): ISavable & ISerializable { return { num: 1, // error! save() {}, load() {}, serialize() {}, deserialize() {}, } } interface ISavable { sa ...

Utilizing Async and await for transferring data between components

I currently have 2 components and 1 service file. The **Component** is where I need the response to be displayed. My goal is to call a function from the Master component in Component 1 and receive the response back in the Master component. My concern lies ...

How can the 'env' property in Nuxt.js be utilized to access the new API?

I have been working on creating news web apps that utilize newsapi.org. To protect my API key, I decided to use the env property in Nuxt.Js. However, I am now encountering a 401 status code from the server. Firstly, I created the .env file in my project d ...

Is it possible to retrieve the distinct errors detected by ESLint?

I'm currently in the process of refactoring a project using TypeScript and React. After adding ESLint, I found over 300 errors scattered throughout the codebase. Facing such a significant number of errors, it's clear that these can't all be ...

What is the rationale behind allowing conflicting types in intersection types?

When presented with two interfaces containing conflicting member types: interface A { x: number } interface B { x: string } It becomes impossible to create an interface that extends both: interface I extends A, B // error TS2320: Interface 'I' ...

Angular2 CLI express server.ts encountered an unexpected import token

Starting an Angular2 project and setting up the server with express and Angular CLI version 1.0.0-beta.25.5 has been challenging for me. The file structure looks something like this: project root |-server |-server.ts |-src |-app When attempting to r ...

"Typescript: Unraveling the Depths of Nested

Having trouble looping through nested arrays in a function that returns a statement. selectInputFilter(enteredText, filter) { if (this.searchType === 3) { return (enteredText['actors'][0]['surname'].toLocaleLowerCase().ind ...

An issue has been identified with React's HTML input maxLength feature where it does not display an error

Within my form, I have an input field that currently does not include validation for a maximum length. <input type="text" className="form-control" id="company" onBlur= ...

Is there a way to utilize the same code in a template without having any redundant duplicates

How can I display the same HTML code in a modal window after clicking on a button in my Angular2 component? Is there a way to achieve this without duplicating the code? html code. ... ... ... <div class="modal fade" id="a" tabindex="-1" role="mod ...

Utilizing external applications within Angular applications

I have the task of creating a user interface for clocker, a CLI-based issue time tracker. Clocker functions as a stand-alone node.js application without any programming interface. To begin tracking time for an issue labeled 123, the command would typically ...

Tips for activating scrolling on a background element even with a modal window currently displayed

Encountering an issue with Angular and Material for Angular - my application contains multiple modals that disable background scrolling when opened. However, there is one notification modal that should not block the background scroll. Despite not having a ...

Developing an Angular 2 Cordova plugin

Currently, I am in the process of developing a Cordova plugin for Ionic 2. The plugin is supposed to retrieve data from an Android device and display it either on the console or as an alert. However, I am facing difficulty in displaying this data on the HT ...

Replace interface with a string

Is it possible to override an interface with a string in TypeScript? Consider this example: type RankList = "Manager" | "Staff" interface EmployeeList { id: string, name: string, department: string, rank: "Staff&q ...

Invoke a static method from within a class in Typescript (Angular HttpInterceptor)

Recently, I've been working on an http interceptor that was functioning smoothly until just yesterday. It consists of static methods, and for some reason, one of them is now causing issues. Here is the error message displayed in the console: my.c ...