TypeScript failed to detect that the type had been narrowed

function encodeToken(value: number | string | null | undefined) {
  if (value !== null && value !== undefined) {
    value = value.toString()
  }

  return encodeBase64(value) // typescript complains this line
}

function encodeBase64(value: string | null | undefined) { ... }

After applying the code, a message from Typescript popped up:

(parameter) value: string | number Argument of type 'string | number' is not assignable to parameter of type 'string'. Type 'number' is not assignable to type 'string'


I'm passing the "value" to encodeBase64, which should be of type string | null | undefined. Any value that is a number will be converted to a string,

If you have suggestions on how to address this issue, please let me know. Thanks!

Answer №1

In the configuration file tsconfig, setting "strictNullChecks" to false can result in this issue.

Here is an example without an 'if' statement that works fine:

function encodeToken(value: number | string | null | undefined) {
  value = value.toString() //narrowed down from `number | string` to `string` after this line
  return encodeBase64(value) 
}

However, the following code does not work as expected:

function encodeToken(value: number | string | null | undefined) {
  if (value !== null && value !== undefined) {
    value = value.toString()
  }
  return encodeBase64(value) //value is still considered `number | string`, so it complains
}

It seems that TypeScript skips some checks when the condition

if (value !== null && value !== undefined)
is present and "strictNullChecks" is set to false.

If you change "strictNullChecks" to true, the issue disappears and the type narrows down correctly from

number | string | null | undefined
to string | null | undefined.

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

The file upload functionality in NextJs 13 API is encountering issues when utilizing formidable

I am currently working on a NextJs 13 project that requires an API capable of handling files sent to it. In order to achieve this, I have utilized the formidable middleware Within my app/api/uploadfile/route.ts file (code has been condensed for clarity) i ...

Incorrect line numbers displayed in component stack trace [TypeScript + React]

Challenge I am currently working on integrating an error boundary into my client-side React application. During development, I aim to showcase the error along with a stack trace within the browser window, similar to the error overlays found in create-reac ...

Running and troubleshooting in VS Code on Windows- Mocha's grep option through launch.json is causing an issue with the message "No test files were located" instead of running only the specified pattern

Setting up basic configuration in launch.json to run all Mocha tests successfully in VS Code on Windows was successful. However, when attempting to add the --grep option for pattern matching behavior, I encountered issues. Despite trying various combinati ...

Transmit data from a child component to a Vue JS page through props, and trigger the @blur/@focus function to access the prop from the parent component

Seeking guidance on working with props in Vue JS. As a newcomer to Vue, I hope that my question is clear. I've included my code snippet below, but it isn't functioning correctly due to missing Vue files. In my attempt to use a prop created in t ...

Modify the ShortDate formatting from "2020/06/01" to "2020-06-01"

I am looking to modify the shortDate format in my template file. Currently, when I try to change it to use "-", it still displays the date with "/". What I actually want is for the output to be formatted as yyyy-MM-dd. <ngx-datatable-column name="C ...

Tips for solving a deliberate circular dependency in an angular provider

If the existing injection token for this provider is available, I want to use it. Otherwise, I will use the specified provider. Below is the code snippet: providers: [ { provide: DesignerRecoveryComponentStore, useFacto ...

Enhance the Monaco editor autocomplete suggestions based on the specific file being edited

I'm interested in enhancing the type hints available in the monaco editor, such as Object, String, or Boolean, with my own custom type. The ultimate goal is for the editor to recognize this new type and offer code completion specific to it. Most of t ...

Utilize ngClass for every individual section

I have completed the implementation of all UI components, which are visually appealing. https://i.sstatic.net/hxJQr.png Here is the data structure I am using: public filters = [ { tag: 'Year', label: 'ye ...

Is there a way to programmatically trigger a CodeAction from a VSCode extension?

Can I trigger another extension's code action programmatically from my VSCode extension? Specifically, I want to execute the resolveCodeAction of the code action provider before running it, similar to how VSCode handles Quick Fixes. Most resources su ...

Encountering an issue where the useMutation function is not recognized on the DecorateProcedure<MutationProcedure> type while attempting to utilize the useMutation feature

Currently, I am utilizing the NextJS app router. I am attempting to invoke a rather straightforward route: import { z } from "zod"; import { createTRPCRouter, publicProcedure } from "~/server/api/trpc"; // document sending user email to waitlist da ...

Can we establish the set values for a function's parameter in advance?

I need to define the available values for a function's parameter in this way: let valueList = [ 'val1', 'val2', 'val3', ]; let getSomething = (parameter: valueList) => { // do something } I want the con ...

GraphQL queries that are strongly-typed

Currently working on a Vue CLI project where I am utilizing axios as my request library. In all the examples I've come across, they use strings for queries like this: { hero { name friends { name } } } Given that I am employing ...

Looping through the json resulted in receiving a null value

When working with typescript/javascript, I encountered an issue while trying to fetch the 'statute' from a data object: {_id: "31ad2", x: 21.29, y: -157.81, law: "290-11",....} I attempted to assign data.law to a variable, but received a typeer ...

Adding TypeScript to your Vue 3 and Vite project: A step-by-step guide

After setting up my project by installing Vue and Vite using the create-vite-app module, I decided to update all the packages generated by 'init vite-app' to the latest RC versions for both Vue and Vite. Now, I am interested in using TypeScript ...

Zod's nativeEnum function verifies the value of an enum

Utilizing a zod schema to validate an object containing an enum field: enum Colour { red: 'Red', blue: 'Blue', } const schema = z.object({ colour: z.nativeEnum(Colour), }); Received data from an API includes color values a ...

What steps should I take to ensure that this test covers all possible scenarios?

I recently started learning React development and am currently exploring testing with Jest and React Testing Library (RTL). However, I'm facing challenges in achieving complete test coverage for the component code below: import { CustomCardActions, ...

Can you clone a repository within another repository and make commits only to the inner repository?

Currently, I am utilizing TypeScript, React, Node.js, and Express in my development project. Within my Node server, I have implemented the use of execSync to clone a separate repository, modify files within it, and ultimately push those changes. The code s ...

Issue with the functionality of extended constraints in class inheritance

I have the following classes: export abstract class Parent<T> { ... public abstract <C extends Parent<T>>clone(): C; } export class Child extends Parent<number> { ... public <Child>clone(): Child { r ...

What is the proper way to access and modify the child component within a parent component?

I am working with nested components as shown below: app.parent.component > app.container.component > app.containeritem.component Here is an example: app.parent.component import ... @Component({ selector:'parent', template: &apos ...

Navigating through the child elements of a parent element in Aurelia

I am currently using Aurelia 1 to construct my application. Right now, I am in the process of creating a custom toolbar element known as custom-toolbar.ts. Within this toolbar, there will be an unspecified number of child elements referred to as custom-too ...