Exploring TypeScript Compiler API: Retrieving the resolved type of the 'this' parameter

Is there a way to properly access the type of an explicit 'this' parameter from a ts.Signature using the compiler API?

// Code being compiled
interface Fn1 {
    (this: Foo): void;
}
const fn1: Fn1 = () => {};

interface Fn2<T> {
    (this: T): void;
}
const fn2: Fn2<void> = () => {};
// Compiler API
function visitVariableDeclaration(node: ts.VariableDeclaration, checker: ts.TypeChecker) {
    const type = checker.getTypeAtLocation(node.type);
    const signatures = checker.getSignaturesOfType(type, ts.SignatureKind.Call);
    const signature = signatures[0];
    // How do I access type of 'this' on signature?
}

Currently, I can call getDeclaration() and look at the parameters, which works for Fn1. However, for Fn2, it won't resolve 'T' to 'void'. When tracing through with the debugger, I can see that signature has a member called 'thisParameter' which seems like it has what I need. But since this is not publicly exposed through the interface, I can't depend on it. Are there any other ways to properly access the type?

Answer №1

If you're looking to extract the parameter type from the signature, you'll need to access the internal thisParameter property. Here's an example:

const thisParameter = (signature as any).thisParameter as ts.Symbol | undefined;
const thisType = checker.getTypeOfSymbolAtLocation(thisParameter!, node.type!);
console.log(thisType); // void

Alternatively, you can retrieve it directly from the type itself. If the ts.Type is a ts.TypeReference, then you can do the following:

const type = checker.getTypeAtLocation(node.type!) as ts.TypeReference;
const typeArg = type.typeArguments![0];
console.log(typeArg); // void

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

Exploring the concept of relative routing within Angular

Update I made the switch from forRoot to forChild based on the responses received. Essentially, I have two issues to address. Let's consider this as a submodule: @NgModule({ imports: [ CommonModule, ARoutingModule, BModule ], decl ...

How should a child component specify the type of component being passed in props?

Consider the following snippet from App.tsx : <Layout header={ <Header/> } </layout> Now, let's take a look at the Layout component : export default function Layout({header, body}: any) { return ( <div className="layou ...

What is the best way to modify the color of a table cell in Typescript with *ngFor loop?

I have an image located at the following link: https://i.sstatic.net/rxDQT.png My goal is to have cells with different colors, where main action=1 results in a green cell and action=0 results in a red cell. Below is the HTML code I am working with: & ...

The getStaticProps() method in NextJS does not get invoked when there is a change in

I have integrated my front-end web app with Contentful CMS to retrieve information about various products. As part of my directory setup, the specific configuration is located at /pages/[category]/items/[id]. Within the /pages/[category] directory, you w ...

What is the process of assigning a value type to a generic key type of an object in typescript?

I am currently working on developing a function that can merge and sort pre-sorted arrays into one single sorted array. This function takes an array of arrays containing objects, along with a specified key for comparison purposes. It is important to ensure ...

Creating a generic array type in TypeScript that includes objects with every key of a specified interface

I am working with an interface called Item interface Item { location: string; description: string; } Additionally, I have a generic Field interface interface Field<T extends object> { name: keyof T; label: string; } I want to create an Arra ...

Obtain Value from Function Parameter

In my Angular project, I have a function that is called when a button is clicked and it receives a value as an argument. For example: <button (click)="callFoo(bar)">Click Me!</button> The TypeScript code for this function looks like ...

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Unable to locate the module from my personal library in Typescript

The Query Why is my ng2-orm package not importing or being recognized by vscode when I try to import Config from 'ng2-orm'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser&a ...

Slim API receives a request from Ionic 5

Seeking assistance with making a GET request from my Ionic application to an API constructed using the Slim Framework. Below is the code snippet of the API: <?php header('Access-Control-Allow-Origin: *'); header('Content-Type: applicati ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Angular: Verify that all services are fully executed before proceeding to the next step

We have adopted Angular for our project. Our component receives data from an API, which is then processed by Data Services. These services transform the data by combining first and last names, rounding dollar amounts, performing calculations, etc. The fina ...

The attribute 'getTime' is not found in the data type 'number | Date'

class SW { private startTime: number | Date private endTime: number | Date constructor() { this.startTime = 0, this.endTime = 0 } start() { this.startTime = new Date(); } stop() { this.endTim ...

Tips for manipulating 2 arrays where the value in one array is reliant on the value in another array

Currently, I have two arrays - arrayGuest and arrayRent. They both contain objects with a common field, GuestID. My goal is to create a list that combines fields from both arrays when their guestIDs match. The structure of the objects is as follows: class ...

Creating an object in JavaScript using an array type初始化数组类型为对象javascript

In my code, there is an interface defined as Products export interface Products{ category: string; imageUrl: string; price: number; title: string; } Within my component, I have a variable named products which is an array of type Product ...

Having trouble locating the .ts module when executing a Node script with experimental modules enabled

I am currently developing a node express project and I need to run a node script from the terminal. Within my project, there are some .ts files that I want to include in the script (MyScript.js). Below is the content of MyScript.js: import get from &apos ...

Animation scaling on the iPhone seems to abruptly jump away once it finishes

Encountering an issue with animations that is causing unexpected behavior on physical iPhone devices but not in the simulators. The problem arises when the background zooms in and then the div suddenly jumps to the left after the animation completes, as sh ...

Explaining the structure of a nested object within a TypeScript declaration file

As I work on my project, I encounter the challenge of importing an object created by a dynamic function. The dynamic nature of the keys on this object poses a problem for the IDE, as it cannot determine what keys are present based on the provided config. T ...

Is there a sophisticated method for breaking down a nested property or member from TypeScript imports?

Just curious if it's possible, not a big deal otherwise. import * as yargs from 'yargs'; // default import I'm looking to extract the port or argv property. This would simplify the code from: bootstrap(yargs.argv.port || 3000) to: ...

Is it possible to eradicate arrow functions in Angular CLI?

I am facing a challenge in running my code on IE11 due to issues with arrow functions. I need to find a way to eliminate them from the build and replace them with function() {}. Even though I have removed them from main.js, they are still present in the v ...