JavaScript now has Type Inference assistance

When attempting to utilize the Compiler API for processing JavaScript code and implementing Type inference to predict types of 'object' in a 'object.property' PropertyAccessExpression node, I encountered some issues. Some simple examples worked as expected, like the first sample below, but most failed. I am unsure if this is the intended way of using TypeScript type inference or if there might be an issue with the code I have written. Any insights would be greatly appreciated. Thank you!

var obj={prop: ''};
var h=obj;
h.prop = ''; //works! 'h' shows as 'obj' type

function fx(arg) {return arg;}
var i=fx(obj);
i.prop = ''; //failed! type of 'i' shows 'any', should be 'obj'

Below is the source code utilizing checker to print inferred type:

var ts = require('typescript');
function visit(node) {
    ts.forEachChild(node, visit);
    console.log( checker.getSymbolAtLocation(node.name));
}

var program = ts.createProgram([process.argv[2]], {lib: ['DOM'], allowJs: true, target: ts.ScriptTarget.ES5, module: ts.ModuleKind.None});
var checker = program.getTypeChecker();
ts.forEachChild(program.getSourceFiles()[0], visit);

Answer №1

Since your function is returning any type, the variable i will also be of type any. Furthermore, the variable i can never be of type obj, only of type {prop: string}.

If you want to make your function more generic, you can modify it like this:

function fx<T>(arg: T): T {return arg;}
var i=fx(obj);

With this modification, the variable i will be of type {prop: string}.

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

Dynamically delete a property from a JSON object

I am currently working on a task that involves removing properties from a JSON object. I need to create a system where I can specify an array of locations from which the fields should be redacted. The JSON request I am dealing with looks like this: { "nam ...

Guide on efficiently navigating a website: utilize selenium python to effortlessly hover the mouse over a sub menu and click on desired options

Seeking to automate a web application called "Maximo" using Selenium in Python, I've successfully managed to log in with credentials and click on buttons. However, I'm stumped on how to hover the mouse over a submenu and perform a click action. ...

React Alert: Please be advised that whitespace text nodes are not allowed as children of <tr> elements

Currently, I am encountering an error message regarding the spaces left in . Despite my efforts to search for a solution on Stack Overflow, I have been unable to find one because my project does not contain any or table elements due to it being built with ...

Is there a safe method to convert an HTML attribute (Javascript Object) into an array using Javascript or JQuery?

I have an HTML element containing a javascript object: <div ui-jq="easyPieChart" ui-options="{ percent: 75, lineWidth: 5, trackColor: '#e8eff0', barColor: ...

Adding an external script to a Vue.js template

Delving into the world of Vue.js and web-pack, I opted to utilize the vue-cli (webpack) for scaffolding an initial application. A challenge arose when attempting to incorporate an external script (e.g <script src="...") in a template that isn't req ...

``The presence of symlink leading to the existence of two different versions of React

Currently, I am working on a project that involves various sub custom npm modules loaded in. We usually work within these submodules, then publish them to a private npm repository and finally pull them into the main platform of the project for use. In orde ...

Activate the mat-menu within a child component using the parent component

Incorporating angular 6 along with angular-material, I am striving to trigger the matMenu by right-clicking in order to utilize it as a context menu. The present structure of my code is as follows. <span #contextMenuTrigger [matMenuTriggerFor]="context ...

I must address the drag-and-drop problem in reverse scenarios

I am currently utilizing react-dnd for drag and drop feature in my color-coding system. The implementation works flawlessly when I move a color forward, but encounters an issue when moving backward. Specifically, the problem arises when shifting a color ...

Having trouble directing my attention towards a Mat card when using viewchildren in Angular

My current challenge is trying to focus on a specific card from a list of mat cards Despite my efforts, I keep encountering an error that reads: Cannot read property 'focus' of undefined Access the code on StackBlitz The desired functionali ...

Customizing SwiperJS to display portion of slides on both ends

I need some assistance with my SwiperJS implementation to replace existing sliders on my website. The goal is to have variable-width slides, showing a landscape slide in the center with a glimpse of the preceding and following slides on each side. If it&ap ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

What steps do I need to take to enable the about page functionality in the angular seed advance project?

After carefully following the instructions provided on this page https://github.com/NathanWalker/angular-seed-advanced#how-to-start, I successfully installed and ran everything. When running npm start, the index page loads with 'Loading...' I ha ...

Listening for events on a canvas positioned beneath another element

I am currently dealing with an issue where I have a mouse move event listener set up on my canvas element. However, there is a div placed on top of the canvas with a higher z-index, which contains some menu buttons. The problem arises when I want the mous ...

Three.js Ellipse Curve Rotation

Purpose My goal is to create an EllipseCurve () where a camera will move. The Approach I Took to Achieve the Goal Below is the code snippet for creating the ellipse: var curve = new THREE.EllipseCurve( 0, 0, 1, 1, 0, 2 * Math.PI, false, ...

In the world of GramJS, Connection is designed to be a class, not just another instance

When attempting to initialize a connection to Telegram using the GramJS library in my service, I encountered an error: [2024-04-19 15:10:02] (node:11888) UnhandledPromiseRejectionWarning: Error: Connection should be a class not an instance at new Teleg ...

Why are double curly brackets used in the JSX syntax of React?

In the tutorial on react.js, a specific usage of double curly braces is highlighted: <span dangerouslySetInnerHTML={{ __html: rawMarkup }} /> Building on this, in the second tutorial titled "Thinking in react" found in React documentation: <sp ...

Ensuring proper execution of the next callback function in an Express get request

I am currently running an express server on nodejs with a specific file structure that I need to convert into a list of links. Included below are my recursive functions for dealing with the file structure. Here are the file structure functions: function ...

Upon executing the `npm start` command, the application experiences a crash

When I tried following the steps of the Angular quickstart guide, I encountered some errors after running "npm start". Here are the errors displayed: node_modules/@angular/common/src/directives/ng_class.d.ts(46,34): error TS2304: Cannot find name 'Se ...

"Dilemma with Displaying a 3-Digit Number in DaisyUI Using Next.Js Countdown Component

Hey there, I'm encountering an issue with the countdown component on my Next.js website using daisyUI. When the number of days exceeds 99, it's not rendering correctly as shown below: https://i.sstatic.net/cWR2tSEg.png https://i.sstatic.net/V0Iv ...

RegEx - Finding exact matches without any additional characters trailing

I am currently trying to find matches in the given strings: 'Los Angeles, CA' 'New York, NY' 'Williamsburg, Brooklyn, NY' by comparing them with the following input strings: 'Los Angeles, CA 90001, USA' 'New ...