Discover the category of an identifier using the TypeScript compiler API

After analyzing the given input file:

function foo (s: string) {
  console.log(s)
}

I am looking to automatically determine the data type of s within console.log(s). My goal is to replicate the functionality that VSCode uses to display the type of s when hovering over it.

https://i.sstatic.net/RkmPO.png

This code snippet represents my current progress.

const ts = require("typescript");

const sourceCode = `
function (s: string) {
  console.log(s)
}
`;

const sourceFile = ts.createSourceFile(
  "test.ts",
  sourceCode,
  ts.ScriptTarget.Latest
);

const functionDeclaration = sourceFile.statements[0];

const identifier =
  functionDeclaration.body.statements[0].expression.arguments[0]; // the s in console.log(s)

const typeChecker = ts.createTypeChecker(ts.createProgram(["test.ts"], {}));
const type = typeChecker.getTypeOfSymbolAtLocation(identifier);

console.log(typeChecker.typeToString(type)); 

The expected result should be "string", but the actual output returned is "any".

Answer №1

I had a bit of trouble figuring out how to make the code provided in the question function properly, but I managed to find a solution that suits my needs.

When dealing with a specific type node, I discovered that by using the getFlags() method, I could obtain a bitmap which can then be compared against typescript.TypeFlags.Undefined to determine if it corresponds to the undefined type.

In situations where we are handling union types, it is necessary to perform this comparison for each type within the typeNode.types array.

The snippet of code that proved pivotal is as follows:

const couldBeUndefined = 
    typeNode.getFlags() & typescript.TypeFlags.Undefined || 
    typeNode.types?.some((n) => n.getFlags() & typescript.TypeFlags.Undefined);

Although this approach did not yield positive results when used alongside the code from the original question, it worked flawlessly within the context of an ESLint rule implementation.

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

Employing a one-time use variable that is asynchronously loaded via a React hook

Currently, I am exploring the functionalities of React's hooks, but I'm encountering a roadblock when it comes to integrating different use cases. The main goal is to create a hook called useNationsAsync that fetches a list of available nations ...

Angular: failure to update a specific portion of the view

I'm currently working on a directive template that features the following code snippet: <div class="colorpicker"> <div>Chosen color</div> <div class="color_swatch" style="background-color: {{ngModel}}">&nbsp;</div> & ...

Issue with ambient contexts error in TypeScript constructor

What is the correct way to create a constructor in TypeScript? I have been researching and trying different approaches, but it seems like the syntax has changed. Here is my latest attempt: car.d.ts declare class Car { constructor(public engine: string ...

What is the best method for incorporating the three.js GLTFExporter into a TypeScript project?

I have been exploring the use of GLTFExporter in a three.js project written in TypeScript. I started with a basic template from https://github.com/pinqy520/three-typescript-starter and made modifications to the render function as follows: console.log(`typ ...

Issue with NestedKeyof type arising from circularly referencing objects

Currently, I am in the process of constructing a library and my task involves implementing NestedKeyof. During my research, I came across the following code snippet: type NestedKeyOf<T extends object> = { [Key in keyof T & (string | number)]: ...

Exploring Immediately Invoked Function Expressions in TypeScript

I came across an interesting article on self-invoking functions in JavaScript by Minko Gechev. This article teaches us how to create a JavaScript function that calls itself immediately after being initialized. I am curious about how we can achieve this in ...

Why does Prettier choose to omit trailing commas?

After creating a brand new Angular application using ng new test-app, I added Prettier to the devDependencies and successfully installed it. I made sure to disable all extensions in VSCode except for Prettier. The issue arises when I configure VSCode to f ...

Encountering issues with property not being found when using connect() with React, Redux, and TypeScript

I'm struggling to correctly define the access of properties and methods on distinct components using the connect() functionality. Here's what I currently have in my redux-folder: /redux/app/hooks.ts import { TypedUseSelectorHook, useDispatch, us ...

Vue3 and Typescript issue: The property '$el' is not recognized on type 'void'. What is the correct way to access every existing tag type in the DOM?

Currently, I am in the process of migrating a Vue2 project to Vue3 and Typescript. While encountering several unusual errors, one particular issue with $el has me puzzled. I have been attempting to target every <g> tag within the provided template, ...

Tips for simulating localStorage in TypeScript unit testing

Is there a method to simulate localStorage using Jest? Despite trying various solutions from this post, none have proven effective in TypeScript as I continue encountering: "ReferenceError: localStorage is not defined" I attempted creating my ...

acquiring environmental variables in TypeScript for node applications

I am struggling with accessing process.env variables in my TypeScript pages. It seems to be a scope issue, which doesn't make sense to me as a beginner in TypeScript. To get my environment variables, I use a YAML file and attach them to the running p ...

Different property 'responseType' types are not compatible

Having trouble making a POST request in Angular 5 that accepts text/plain as a response. The method being called in Angular expects a JSON response, causing an error when trying to parse the response. Attempted to call the method with parameter {responseT ...

Incorporate a New Feature into my NPM Package

I've been searching high and low for an answer to this, but I'm still stuck. I'm working on a module in Angular 2 with ng-module, and everything is functioning properly. However, I'm struggling to assign a property to another property w ...

Unable to generate a store using reducer in TypeScript and Redux

I am having trouble creating a store using Redux and TypeScript. Here is my actions.js file: import { Action } from 'redux'; export interface ITodoAction extends Action { todo:string; } export const ADD_TODO:string = 'ADD_TODO'; ...

The error "Prop does not exist on type 'PropsWithChildren'" occurs when attempting to dispatch an action with react-redux

When attempting to dispatch the action, I am encountering this error: The error message reads: Property 'fetch_feed_loc' does not exist on type 'PropsWithChildren<{ onSubmitForm: any; }>'. Another error states: Property &apos ...

How to toggle element visibility when hovering in Angular?

I've set up an angular material card that includes a close button (marked with an "x"). My goal is to initially hide the "x" button and only display it when hovering over the card. Here is the code snippet for the card: <mat-card> <mat- ...

Linking Redux to the highest level of my application is not functioning as expected

I have been attempting to troubleshoot this code for quite some time now, but I am struggling to identify the issue at hand. My main goal is to establish a connection between my top-level application and the redux store. However, every time I try, the stor ...

Combining mismatched forms. For instance, form 'A' cannot be attributed to form 'B'

How can I combine different types? type TheseTypes = typeof TouchableNativeFeedback & typeof TouchableWithoutFeedback & typeof TouchableHighlight & typeof TouchableOpacity; const Button: React.FC<CustomProps> = (props) => ...

An error occurred while trying to access properties of null, specifically the `_rawValidators` property

I recently upgraded an app from angular 8 to angular14 and encountered a problem with a form array. The error message I'm seeing is cfs-detail.component.html:13 ERROR TypeError: Cannot read properties of null (reading '_rawValidators'). It ...

The Battle of Identifiers: Named Functions against Anonymous Functions in TypeScript

When it comes to performance and performance alone, which option is superior? 1) function GameLoop() { // Performing complex calculations requestAnimationFrame(GameLoop); } requestAnimationFrame(GameLoop); 2) function GameLoop() { // ...