What could be the reason why the getParentWhileKind method in ts-morph is not returning the anticipated parent of the

Utilizing ts-morph for code analysis, I am attempting to retrieve the parent CallExpression from a specific Identifier location. Despite using

.getParentWhileKind(SyntaxKind.CallExpression)
, the function is returning a null value.

Why is this happening? I clearly have the relevant CallExpression which should be the parent of the identified foo.

What key element am I overlooking? And how can this issue be resolved? (aside from resorting to using multiple getParent() calls.)

import { Identifier, Project, SyntaxKind } from "ts-morph";
console.clear();

const project = new Project();
const sourceFile = project.createSourceFile(
  "test.ts",
  `

  const fn = () => {
    chain.foo.bar('arg');
  }
`
);

const a = sourceFile.getDescendants().find((d) => d.getText() === "foo");

console.log({ a: a?.getParentWhileKind(SyntaxKind.CallExpression) });

Visit codesandbox.io

Answer โ„–1

RetrieveAncestorOfKind functions in a slightly different way compared to this code snippet. In the documentation, it is explained as follows:

Ascends through the ancestors of the node while the ancestor matches the specified syntax kind. If the initial parent is not of the specified kind, it will return undefined.

Given that the immediate parent of bar does not match a call expression, the function will simply return undefined. I recommend using RetrieveAncestor to iterate through each ancestor until you encounter your first CallExpression.

const ancestor = x?.RetrieveAncestor((node) => {
  if (node.isKind(SyntaxKind.CallExpression)) {
    return false;
  }
  
  return true;
});

This may seem counterintuitive since you are returning false upon finding the desired node. However, by doing so, you are signaling ts-morph to stop further searching.

Answer โ„–2

If you're looking to enhance your code using the ๐ŸŠPutout code transformer, there are template values available for you to utilize.

For example, if you need to remove foo from an expression like this:

chain.foo.bar('arg');

You can easily achieve the desired result:

chain.bar('arg');

To implement this transformation, consider using a setup similar to this one:

// https://git.io/JqcMn

export const report = () => `Drop 'foo'`;

export const replace = () => ({
    '__a.foo.__b(__c)': '__a.__b(__c)',
});

Feel free to manipulate the linked values __a, __b, and __c in any way that suits your needs.

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 power of D3, TypeScript, and Angular 2

I am facing challenges incorporating D3 v4 with Angular 2 (Typescript). While exploring D3 v4, I have referred to several solutions on StackOverflow without success. I have imported most of the necessary D3 libraries and typings (utilizing TS 2.0) and adde ...

What is the best way to load a component every time the function is called?

Currently, I am utilizing Angular and endeavoring to create reusable actions such as bulk updates, deletes, and deactivations. I have incorporated all of these actions into another component and aim to use it as a generic method. This implies that I have ...

What is the best approach to breaking down attributes upon import according to the theme?

Hey there! Here's the thing - I have this file called <code>colors.ts:</p> export const black = '#0C0C0C'; export const blue = '#22618E'; Whenever I need to use a color, I import it like so: import {black} from 'S ...

Exploring the possibilities of integrating jQuery into Angular 2 using Javascript

import {Component, ElementRef, OnInit} from 'angular2/core'; declare var jQuery:any; @Component({ selector: 'jquery-integration', templateUrl: './components/jquery-integration/jquery-integration.html' } ...

Implement TypeScript to include type annotations on functions' parameters using destructuring and the rest syntax

Issues with Typing in Typescript Trying to learn typing in Typescript has presented some difficulties for me: I am struggling to convert this code into a strongly-typed format using Typescript. const omit = (prop: P, { [prop]: _, ...rest}) => rest; ...

What is the reason behind not being able to pass an instance of B to an argument a of type T in Typescript generics when T extends B?

There is a problem with my code: class X<T extends B> [...] // this.p.a :: B | null methodA(a: T):void {[...]} methodB(): void { if(this.p.a){ // :: B this.methodA(this.p.a) // Error My intention was for T to be any type that exten ...

What is the best way to focus on a particular version of TypeScript?

After upgrading my Angular 2 project to RC1 and the router to v3 alpha3, I encountered the following errors: node_modules/@angular/router/directives/router_outlet.d.ts(10,14): error TS1005: '=' expected. It appears to be a TypeScript version is ...

Is there a way to modify a single object within an array?

Here is the HTML representation of my data: https://i.sstatic.net/VbKQ4.png page.html <ul id="elements"> <li *ngFor="let elem of fetchdata" (click)="log(elem)"> {{elem.title}} {{elem.description}} </li> ...

Using TypeScript with React - employing useReducer with an Array of Objects defined in an Interface

After implementing the given component, I encountered an error related to my useReducer function. The specific error message states: "No overload matches this call..." and provides details on how the parameters are not compatible. import React, {useReducer ...

Angular2: PrimeNG - Error Retrieving Data (404 Not Found)

I'm facing an issue with using Dialog from the PrimeNG Module. The error message I keep getting is: Unhandled Promise rejection: (SystemJS) Error: XHR error (404 Not Found) loading http://localhost:4200/node_modules/primeng/primeng.js I followed the ...

How to efficiently fetch Redux state through reducers with an action-based approach

Utilizing Redux actions to manage a list of contacts, I am facing an issue where I am unable to retrieve the actual state contact. Despite setting the contact in the action, all I receive is the contact set within the action itself. Can someone guide me on ...

Avoiding the restriction of narrowing generic types when employing literals with currying in TypeScript

Trying to design types for Sanctuary (js library focused on functional programming) has posed a challenge. The goal is to define an Ord type that represents any value with a natural order. In essence, an Ord can be: A built-in primitive type: number, str ...

In Next.js, a peculiar issue arises when getServerSideProps receives a query stringified object that appears as "[Object object]"

Summary: query: { token: '[object Object]' }, params: { token: '[object Object]' } The folder structure of my pages is as follows: +---catalog | | index.tsx | | products.tsx | | | \---[slug] | index.tsx | ...

Checking for unnecessary properties in Typescript with vue-i18n

Let's consider two different languages represented in JSON format: jp.json { "hello": "ใ“ใ‚“ใซใกใฏ" } ge.json { "hello": "hallo", "world": "welt" } Now, we are going to com ...

What is the best way to locate every object based on its ID?

Currently, I am facing an issue where I have a list of IDs and I need to search for the corresponding object in the database. My tech stack includes Nodejs, Typescript, TypeORM, and Postgres as the database. The IDs that I am working with are UUIDs. ...

What is the best way to identify errors in an express listen callback function?

My current code is set up to verify if there was an error while initiating Express: express() .listen(port, (err: Error) => { if (err) { console.error(err); return; } console.log(`Express started`); ...

What could be causing the issue of Vuejs 3.3 defineModel consistently returning undefined?

I am currently working with Nuxt version 3.5.1 and Vuejs version 3.3, however, I am encountering an issue where the defineModel macro always returns undefined. I am unsure why this is happening? <template> <input v-model="count"& ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Exploring the power of Next.js, Styled-components, and leveraging Yandex Metrica Session Replay

I'm currently involved in a project that utilizes Next.js and styled-components. In my [slug].tsx file: export default function ProductDetails({ product }: IProductDetailsProps) { const router = useRouter(); if (router.isFallback) { return ( ...

Upon refreshing the page, the Vuex store getter displays [__ob__: Observer]

After each page refresh, my Vuex store getter returns [__ob__: Observer]. The version of Vue being used is 2.2.3 along with TypeScript. Initially, the data loads correctly from an external API, but when utilizing the getter, it fails and requires another ...