Are there any APIs available for creating TypeScript reflection programmatically?

My goal is to extract metadata associated with Props objects. For instance, the output I am looking for could be as simple as:

{
  suffix: 'string',
  count: 'number',
  increment: 'function'
}

I understand that this task can be quite complex, especially considering that each prop could potentially be a union type. However, I am hoping to establish a starting point and I am willing to forego capturing the complete type information in this reflection.

The manual approach would involve using a parser to obtain the AST of the Props object. However, this poses a significant amount of work as any of these types might reference types from other files. This means I would need to write a script capable of navigating through imports and dealing with other potential complications that I may have overlooked.

Before diving into such a daunting task, I am curious if there exists an API that can handle this already - whether it's an official TypeScript tool or something developed by another popular tool. Code editor plugins must somehow retrieve this information to offer autocomplete features.

https://i.sstatic.net/1m6U8.png

So far, I have come across this project: https://github.com/plumier/tinspector. However, it doesn't appear to be widely used and does not seem to follow imports, which is my primary concern.

Thank you!

Answer №1

To perform static analysis of TypeScript source code, one option is to utilize the TypeScript compiler available as an NPM package.

import * as ts from 'typescript';
import * as fs from 'fs';

/** Initialize AST root for the entire program/file */
const ast = ts.createSourceFile(
  'source-file.ts',
  fs.readFileSync(`${process.cwd()}/src/source-file.ts`).toString(),
  ts.ScriptTarget.ES2018,
  true
);

In order to handle your specific use case, you would need to explore the TypeScript compiler API. In a general sense, you can navigate the AST and identify different node types that are relevant to your application, such as interfaces.

switch (node.kind) {
  case ts.SyntaxKind.InterfaceDeclaration:
    // Process interface declaration node by diving deeper into another function
    break;
  // Repeat for other cases...
}

As mentioned, the complexity of utilizing the compiler API depends on your objectives. However, working with it in your NodeJS backend should be relatively straightforward.

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

What is the best way to implement an EventHandler class using TypeScript?

I am in the process of migrating my project from JavaScript to TypeScript and encountering an issue with transitioning a class for managing events. To prevent duplicate option descriptions for adding/removing event listeners, we utilize a wrapper like thi ...

What steps can be taken to troubleshoot a TypeScript-powered Node.js application running in WebStorm?

Seeking advice on debugging a node.js application utilizing TypeScript within WebStorm - any tips? ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

Nestjs struggles with resolving dependencies

Having trouble finding the issue in my code. (I'm still new to nestjs and trying to learn by working on some apps). The console log is showing the following error: Nest can't resolve dependencies of the UrlsAfipService (?). Please ensure tha ...

The custom validation in nestjs is throwing an error due to an undefined entity manager

I've been working on developing a custom validation for ensuring unique values in all tables, but I encountered this error: ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'getRepository') TypeError: Cannot read proper ...

Sending parameters with a linked Get request leads to a 404 error page

Exploring how to interact with an external API using a TS/Express server. The user will choose a product, triggering a GET request to the server, which then queries the external API for pricing data. This is a project for fun and learning purposes, so ple ...

Script execution is disabled on this system preventing the loading of content - ANGULAR V14

Every time I try to run my Angular project or any ng command, I keep encountering the following error message: ng : File C:\Users\achra\AppData\Roaming\npm\ng.ps1 cannot be loaded because running scripts is disabled on this ...

When the appdir is utilized, the subsequent export process encounters a failure with the error message "PageNotFoundError: Module for page /(...) not

I have implemented NextJS with the experimental appDir flag and organized my pages in the following manner: https://i.stack.imgur.com/M7r0k.png My layout.tsx file at the root and onboard look like this: export default function DefaultLayout({ children }) ...

How can you determine in .NET Remoting whether an object is being utilized as a remotable object?

Although .NET Remoting has been replaced by WCF, I am curious about a specific academic question. Imagine having a remotable class defined like this: public class MyObject : MarshalByRefObject { } Then, consider client code that creates an instance of M ...

Angular JSON converter - Transform XML data to JSON format

Struggling to convert XML API response to JSON using xml2js library, facing issues with getting 'undefined' in the console. Here is my API service: export class WordgameService { public apiUrl = "http://www.wordgamedictionary.com/api/v1/reference ...

Unable to locate the module styled-components/native in React Native

When adding types in tsconfig.json to remove TypeScript complaints and enable navigation to a package, the code looks like this: import styled, {ThemeProvider} from 'styled-components/native'; The package needed is: @types/styled-components-re ...

Discovering a specific string within an array of nested objects

Seeking guidance on creating a dynamic menu of teams using JavaScript/TypeScript and unsure about the approach to take. Here is an example dataset: const data = [ { 'name': 'Alex A', 'agentId': '1225& ...

What steps should I take to ensure the successful function of the App Routing system in this scenario?

After creating an Angular App, I encountered a challenge in one of my services. When I call the http.post method and subscribe to it, I aim to redirect to the previous page with a parameter (e.g., "http://localhost:3000/profile/aRandomName"). Unfortunately ...

Ensuring data types for an array or rest parameter with multiple function arguments at once

I am looking for a way to store various functions that each take a single parameter, along with the argument for that parameter. So far, I have managed to implement type checking for one type of function at a time. However, I am seeking a solution that al ...

Using Typescript, create an instance of a generic class and store the specific type value in a variable

How can you instantiate a generic class in TypeScript? (1) When the value of the type parameter is known during compilation, (2) when the type to use as the parameter is passed as a string? Click here for an example interface ITheValue { TheValue: strin ...

TS: Utilizing a generic parameter in an overloaded function call

This piece of code encapsulates the essence of what I'm trying to achieve more effectively than words: function A(a: string): string; function A(a: number): number; function A(a: any) { return a; } function B<T extends number | string>(arg: T): ...

How come the Angular8 form status registers as VALID even if the input fields are empty?

The following is the structure of the component: export class SchedulerComponent implements OnInit { schedulerForm : FormGroup; constructor(private fb: FormBuilder, private schedulerReportService: SchedulerReportService) { this. ...

Is there a way to expand the return type of a parent class's methods using an object

Currently, I am enhancing a class by adding a serialize method. My goal is for this new method to perform the same functionality as its parent class but with some additional keys added. export declare class Parent { serialize(): { x: number; ...

Transforming the unmanaged value state of Select into a controlled one by altering the component

I am currently working on creating an edit form to update data from a database based on its ID. Here is the code snippet I have been using: import React, {FormEvent, useEffect, useState} from "react"; import TextField from "@material ...

What is the correct way to utilize refetchOnReconnect for a builder.mutation endpoint in @redux/toolkit/query?

I'm having an issue with the Redux refetchOnReconnect option not working even after I have called the setupListener(store.dispatch) in my redux store.tsx file and set refetchOnReconnect=true to the endpoint hook call. store.tsx file 'use client& ...