Is it possible that Typescript does not use type-guard to check for undefined when verifying the truthiness of a variable?

class Base {}

function log(arg: number) {
    console.log(arg);
}

function fn<T extends typeof Base>(
    instance: Partial<InstanceType<T>>,
    key: keyof InstanceType<T>,
) {
    const val = instance[key];
    if (val) {
        log(val);
    }
}

Check out the code in the TS Playground: here

The issue arises when trying to assign 'undefined' to a parameter that expects a 'number.' This can be solved by using the nullish coalescing operator like so: log(val ?? 0).

It may seem surprising that log(val ?? 0) works, as val could potentially be a truthy value that is not a number. However, TypeScript does not throw an error in this scenario.

Answer ā„–1

This issue has been widely recognized. For a deeper understanding of what's happening within the type checker, you can refer to this insightful comment:

The main problem lies in the fact that the narrowed type of fooAnchor is quite complex. The original type is Partial<FooAnchorMap>[keyof TMap], which doesn't simplify neatly into a type that can be definitively assigned to HTMLElement.

Efforts are underway with this ongoing work to address the issue. In the meantime, only temporary solutions exist.

function fn<T extends typeof Base>(
    instance: Partial<InstanceType<T>>,
    key: keyof InstanceType<T>,
) {
    const val: InstanceType<T>[keyof InstanceType<T>] | undefined = instance[key];
    if (val) {
        log(val);
    }
}

Link to playground

You will encounter the following error message:

 Type 'InstanceType<T>[string]' is not assignable to type 'number'.

Answer ā„–2

The undefined concept is a distraction; the issue here is due to the enabled setting of strictNullChecks. This means that unless you specify

function log(arg: number) {
    console.log(arg);
}

as

function log(arg: number | undefined) {
    console.log(arg);
}

you will receive an error whenever passing in anything that could potentially result in undefined. Disabling strictNullChecks would resolve this particular error (while possibly introducing others with the given code); alternatively, ensuring that undefined is handled before being passed in (e.g. ?? 0) can also address it.

I find it interesting that log(val ?? 0) seems to work. If val is a non-numeric truthy value, shouldn't this cause an error since log() expects a number input?

If val ?? 0 does not result in a number and log() requires a number input, it should indeed trigger an error in the scenario where a non-numeric truthy value is supplied. This behavior correctly triggers an error in my experience on the playground. Can you provide an example where it behaves differently?

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

Instead of using a string in the createTextNode() function, consider utilizing a variable

I am attempting to use JavaScript to add another list item to an unordered list. I want the list item to display dynamic content based on a pre-existing variable. While I can successfully append a list item by using a string, things go awry when I try to i ...

Steps to effectively pass parameters in a function object literal

As a JavaScript beginner utilizing an object literal pattern, I am attempting to pass integers as min and max parameters to a function in order to retrieve a random number for use in another function called "interaction". However, I encountered the error m ...

The Puppeteer software does not automatically shut down the browser once the task is complete

Currently, I have set up puppeteer on my Ubuntu server with Express and Node.js like so: var puppeteer = require('puppeteer'); var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/&ap ...

A Greasemonkey script for organizing and categorizing webpage elements

I've been working on a script to enhance the functionality of Facebook's find friends page by organizing suggested friends based on mutual connections. If you're interested in checking out the code, you can find it right here: http://pasteb ...

Utilize RequireJS to modularize scripts in an organized manner

Recently, I was working on a web application and wanted to organize it into modules. After some research, I discovered that RequireJS is the most suitable tool for this task. By reading documentation and tutorials, I managed to come up with the following c ...

Using TypeScript with AWS Lambda: To package imports or not to package? Alternatively: Error in Runtime.ImportModule: Module '@aws-sdk/...' not found

I have been working with the code in my lambda.ts file, attempting to execute it on an AWS Lambda: import 'aws-sdk' import { /* bunch of stuff... */ } from "@aws-sdk/client-cloudwatch-logs"; import {Context, APIGatewayProxyResult} from ...

Having trouble sending specific data using the jQuery Form Plugin ajaxForm feature

Currently, I am utilizing two jQuery plugins: plupload and jQuery Form Plugin ajaxForm. Everything is functioning well except for one issue: I am unable to send the file.name (using ajaxForm) of a previously uploaded file with plupload. To elaborate more ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

How can I personalize a Leaflet popup with image thumbnails and additional customization options?

I've been researching and trying out different solutions, but so far none of them have worked for me. My goal is to dynamically add a title, image, address, and name to popups on my leaflet map as data comes in. However, I'm experiencing some cha ...

Adjust CardMedia Images to match their content in the new MUI 5 version

Iā€™m looking to have my images fully fill the CardMedia component. However, because they are of varying sizes, some end up being cropped like this: https://i.stack.imgur.com/JHIrT.png Additionally, when resizing the images, some get cut off as well: ht ...

Tips for preventing CORS errors while rendering an image on a canvas

Working on a project for my coding bootcamp where I need to overlay bandaids on an image of a bear using canvas. The main challenge is to check the color of the area that users click to ensure they don't put bandaids on the white space around the actu ...

How come a colon within a function's body does not result in an error in JavaScript?

During my coding journey, I encountered a situation where I was attempting to return an object from an arrow function. However, I noticed that the code snippet below was simply returning undefined. After some investigation, I determined that the curly br ...

In Angular, encountering difficulty accessing object members within an array when using custom pipes

Here is a custom pipe that I have created, but I am facing an issue accessing the members of the customfilter array, which is of type Item. import { Pipe, PipeTransform } from '@angular/core'; import {Bus} from '/home/pavan/Desktop/Pavan ...

How can an array of objects be sent as a query string to the endpoint URL in React?

I'm currently developing a react application and facing the challenge of dynamically constructing and appending query strings to URLs. This is necessary because I have a shared base endpoint for all links, but each link may require different parameter ...

Is it possible to utilize hooks such as 'useState' within an async/await server component?

'use client' async function Teachers (){ const response = await fetch('http://localhost:8000/teachers', }) const data = await response.json(); const [showNames , setShowNames] = useState(false); // Unable t ...

Javascript/jquery functions perfectly in all browsers except Firefox

This particular piece of code seems to be functioning properly in Internet Explorer 8, Chrome, and Safari, however, it is not working as expected in Firefox: <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></scr ...

Implementing a gradient effect on a specific image element within an HTML canvas with the help of jQuery

Currently, I'm working on an HTML canvas project where users can drop images onto the canvas. I am looking to implement a linear gradient effect specifically on the selected portion of the image. My goal is to allow users to use their mouse to select ...

"Seamlessly Integrating AngularJS with WebGL for Stunning Canvas Inter

I am new to AngularJS and curious about its compatibility with HTML5 Canvas or WebGL. Are there any tutorials available on how to integrate AngularJS into a view that uses these technologies? I have noticed some games claiming to be developed with Angular ...

There is a lag in the loading of css stylesheets

We created a single-page company website that utilizes three different stylesheets connected to the index.html. By clicking a button, users can switch between these stylesheets resulting in changes to colors, images, and text colors. However, Issue 1: The ...

Dealing with cross-origin error issues when using json.parse in React / MERN development

My data structure functions correctly when I use console.log: console.log(JSON.parse([values.category2]).needed_skills); However, when I pass the output of JSON.parse([values.category2]).needed_skills to a component in my application, the entire system c ...