Determining whether a Typescript AST node represents a javascript native function

How can I determine if an AST node in TypeScript represents a valid JavaScript function, as opposed to a custom method?

Here's what I'm thinking:

function isJavascriptFunction(node: ts.Node): boolean {
    // -----
}

For instance, given the code:

const a = b.slice(1);

The AST looks like this:

CallExpression
    PropertyAccessExpression
        Identifier
        Identifier

In this case, the second Identifier is the JavaScript function "slice", so my function would need to return true.

Any suggestions on how to approach this problem?

Appreciate your assistance

Answer №1

After much searching, I have finally discovered a solution.

Initially, I need to verify whether my Node is the second child of a PropertyAccessExpression and if its grandparent is a CallExpression.

From these criteria, I can determine that my node represents a call to a function.

Next, I must confirm if this function is a built-in JavaScript function. To do so, I must locate the Node's Definition (where the slice function is defined in the example). This information can be found in the corresponding Symbol related to the node.

Subsequently, I search for the file path where this function is declared. If the path matches /typescript\/lib/, it indicates that it is a native TypeScript (or JavaScript) function.

I carry out these tasks using the impressive library ts-morph, though it is also possible to utilize the native ts library.

   /**
    * Determines if a node represents a function or method call
    * Example: a.slice(1)
    * @param node      // The node to be checked
    */
  isFunctionCall(node: Node): boolean {
       return node?.getParent()?.getParent()?.getKind() === SyntaxKind.CallExpression && isSecondSon(node);
   }


   /**
    * Checks if a given node is the second child of its parent
    * @param node      // The node to be checked
    */
   isSecondSon(node: Node): boolean {
       if (!node?.getParent()) {
           return false;
       }
       return node?.getChildIndex() === 2;
   }

if (isFunctionCall(node)) {
   const identifier = node as Identifier;
   const definition = identifier.getDefinitions()?.[0];
   const path = definition.getSourceFile().getFilePath();
   return path.match(/typescript\/lib/);
}

I hope this explanation proves beneficial to someone in need.

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

Invoking a greasemonkey script when a user interacts with a button

For a script I wrote, I added an extra column and link in each row. However, the issue is that I want the links to trigger a function in my greasemonkey script and pass a variable to it. I have learned that because greasemonkey operates in a sandbox, achi ...

Is there a way to customize the color of the icons on material-table for the actions of onRowAdd, onRowUpdate, and onRowDelete

I recently experimented with the material-table library to perform basic CRUD operations. Utilizing onRowAdd, onRowUpdate, and onRowDelete, I was able to incorporate icons for each function. However, I am interested in changing the color of these icons. Ca ...

Retrieve the formcontrolname property of a FormGroup within a FormArray

I am currently facing an issue with my code. In my FormGroup, I have a FormArray containing 3 FormControls. My goal is to iterate through the FormArray and display the values of each control in a form. However, I am unsure about what to use for the formCon ...

What is the method for assigning a value to an attribute in HTML?

Is there a way to assign a function's value to an HTML attribute? For example, setting the attribute value to the value returned by the function foo. foo () : string { return "bar"; } I attempted the following without any success. <input type="b ...

Creating a monorepo project in JavaScript that mimics the structure of Visual Studio projects

When working on a typical .NET Core project (with Visual Studio 2019), the structure typically looks like this: Example/ |-- Example.Common/ | |-- FileExample1.cs | |-- FileExample2.cs | `-- Example.Common.csproj |-- Example.WebAPI/ | |-- Control ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

Patience is key as you await the element to load and smoothly render the data in vue.JS

Is there a way to ensure that the graph is only rendered and filled with data after the data has been returned from the backend? Currently, even though the data is returned, the graph appears blank. Here is my JavaScript code: methods: { refresh( ...

Is the Typescript index signature limited to only working with the `any` type?

I recently made changes to my interface and class structure: export interface State { arr : any[]; } export const INITIAL_STATE: State = { arr: [] }; This updated code compiles without any issues. Now, I decided to modify the Interface to incl ...

The mssql node is experiencing an issue where it is unable to accept work due to the pool being

Recently, I encountered an issue with my node js app that utilizes the npm mssql module. Despite purchasing a cloud Windows 2012 server, I faced an error when trying to execute a stored procedure. The error is thrown at ps.prepare("exec usp_Get_Cars @para ...

cors library returns success messages, not errors

Currently, I am working on implementing the cors package within a node and express environment to validate whether the requesting domain can access my resources. Setting up the validation part following the official documentation was not an issue. However, ...

Issues arise when trying to update the modelValue in unit tests for Vue3 Composition API

Recently delving into Vue, I am currently engaged in writing unit tests for a search component incorporated in my project. Basically, when the user inputs text in the search field, a small X icon emerges on the right side of the input box. Clicking this X ...

NodeJS can be used to convert JSON data into an XLSX file format and allow for

I am currently working on a project in nodejs where I need to convert JSON data into XLSX format and then download it to the client's browser. I have been using the XLSX npm module to successfully convert the JSON data into a Workbook, however, I am f ...

Retrieve isolated scope of directive from transcluded content

I am not certain if it is possible, but I am essentially looking for a reverse version of the '&' isolate scope in AngularJS. You can check out this Plunkr to see an example. In essence, I have created a custom directive that provides some r ...

The TypeScript compiler throws an error when encountering nulls in conjunction with the isNull function

Whenever I set strictNullChecks: true in tsconfig.json and utilize the isNull function for null checks, the compiler throws the error TS2531: Object is possibly 'null'. Interestingly, isNull doesn't trigger any errors in VsCode, however, the ...

Issue with setting .mtl properties in a custom shader in three.js

In my custom three.js application, I am loading an OBJ/MTL model for rendering. I am trying to apply a custom shader to the model, but the color and specular uniforms that I manually pass to the RawShaderMaterial are not updating correctly. Instead, they a ...

Converting JSON object to a string

I have an object that contains the value "error" that I need to extract. [{"name":"Whats up","error":"Your name required!"}] The inspector displays the object in this format: [Object] 0: Object error: "Your name required!" name ...

Troubleshooting issues with JavaScript progress bar functionality

I have implemented a progress bar using HTML5, JavaScript and Ajax to showcase file uploads in PHP. The issue I am facing is that the progress bar is not displaying the progress correctly. In addition to that, the echo statements in the PHP code are no ...

Can someone help me identify the issue with my JavaScript code?

Recently, I attempted to transfer data from JavaScript to HTML using Angular. Here is the code snippet: phonecatControllers.controller('start', ['$scope', function($scope){ $scope.lloadd=true; console.log('data - '+$ ...

A conflict with the Ajax file is causing an automatic logout

In my Rails application, there is a page with a table that uses partial AJAX to increase the capacity attribute in a time entity. You can view the visual representation of the table here. By clicking the plus/minus button, the capacity attribute increases ...

Encountering a 500 error while trying to access the document page in a Next.js Vercel app after

I am facing an issue with my next.js app hosted on Vercel, where I keep receiving a 500 error when trying to load a specific page. Upon inspecting the Chrome dev tools, I noticed that the error occurs when attempting to access the /dashboard page. Despite ...