The attribute 'split' is not found on the never data type

I have a function that can update a variable called `result`. If `result` is not a string, the function will stop. However, if it is a string, I then apply the `split()` method to the `result` string.

This function always runs successfully without crashing. But TypeScript raises an error claiming:

"Property 'split' does not exist on type 'never'."

Take a look at the code snippet below:


function processData() {
    let data = userData[category] as { [key: string]: {} };

    ["employees", "tech"].forEach((key) => {
        if (!data[key]) return;
        return (data = data[key]);
    });

    if (typeof data !== "string") return null;
    
    // do more operations
}

How can this type issue be resolved?

Answer №1

You have set the result variable to a null value explicitly:

let result = null;

As it stands, the condition:

if (typeof result !== "string") 

will always be true. Therefore, the code that follows with return result... will never be executed.

If you adjust your function slightly to accept result as an argument, then the condition will work correctly and TypeScript will not raise any issues:

function foo(result: string | null) {  // accepts a possibly null result
    // perform operations
}

Answer №2

When looking at your code example, the result seems to be of type null and only null

If you want to allow it to accept both null and string, you must explicitly declare that

function foo(){
let result: string | null = null
// carry out some operations
if (typeof result !== "string") return null;
// do more operations
return result
        .split("__")
        .map((word:string) => word.toUpperCase())
        .join("")
    : result;
  }

In addition, depending on your TypeScript version, you can simplify these checks to make it a bit more succinct (using null coalescing and optional chaining)

function foo(){
  let result: string | undefined;

  // operate on result to potentially turn it into a string
  // continue with more operations

  return result
        ?.split("__")
        .map((word:string) => word.toUpperCase())
        .join("") ?? null
}

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

Troubleshooting import errors with Typescript for C3 and D3 libraries

I have recently started working on a project using the C3 graphing library within an Ionic2/Angular2 TypeScript setup. After installing C3 via npm and the type definitions via tsd, I imported it into my own TypeScript file like this: import {Component} fr ...

Limiting the displayed portion of a table and implementing scrolling instead

I am currently working with a static HTML template that contains the following code: <table> <thead></thead> <tbody></tbody> </table> Using jQuery and AJAX, I am dynamically adding and removing rows and columns ...

Steps for submitting a form once all inputs have been verified

$('#f_name, #l_name').change(function(){ if($(this).val().length < 2) { $(this).css('border', '1px solid red'); alert('names must be at least 2 symbols'); check ...

Is this code in line with commonly accepted norms and standards in Javascript and HTML?

Check out this Javascript Quiz script I created: /* Jane Doe. 2022. */ var Questions = [ { Question: "What is 5+2?", Values: ["7", "9", "10", "6"], Answer: 1 }, { Question: "What is the square root of 16?", Values: ["7", "5", "4", "1"], Answer: ...

Switching CommonJS modules to an ESM syntax for better compatibility

I'm currently facing a challenge in grasping the process of importing CommonJS modules into an ESM syntax. Specifically, I am working with the library url-metadata. This library provides a top-level export as a callable function, which deviates from t ...

Unlocking the Power of FusionAuth in NativeScript: A Guide

While attempting to utilize a library based on nativescript documentation, I encountered an issue where certain modules like net and tls were not being automatically discovered. After using npm install to include tls and net, the problem persisted with t ...

"Learn how to easily send media files stored on your local server via WhatsApp using Twilio with Node.js and Express

Whenever I attempt to send the PDF file created through WhatsApp, an error pops up preventing me from viewing it. easyinvoice.createInvoice(data, function(result) { //The response will contain a base64 encoded PDF file ...

The method window.scrollTo() may encounter issues when used with overflow and a height set to 100vh

Suppose I have an HTML structure like this and I need to create a button for scrolling using scrollTo. However, I've come across the information that scrollTo doesn't work well with height: 100vh and overflow: auto. What would be the best way to ...

Utilizing Express JS to make 2 separate GET requests

I am facing a strange issue with my Express API created using Typescript. The problem revolves around one specific endpoint called Offers. While performing operations like findByStatus and CRUD operations on this endpoint, I encountered unexpected behavior ...

What steps can be taken to choose a particular class when multiple classes share the same name?

Imagine having a table layout like this: <table class="first-table" border="1" width="400px"> <tr> <td><?php echo $row_cond['title']; ?></td> <td><a class="more" href="#" onClick="slideup() ...

Setting a default value within an input tag: A step-by-step guide

const [userData, setUserData] = useState([]); const handleUserInfo = (id) => { fetch(`https://602e7c2c4410730017c50b9d.mockapi.io/users/${id}`) .then(res => res.json()) .then(data => setUserData(data)) } <inpu ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

What is the best way to align a TabPanel component at the center using React Material UI

As I attempt to compile a list of articles while switching to a list of other entities in React + material UI, I have encountered some difficulties. Specifically, I am struggling to center the Card displaying an article in alignment with the centered Tabs. ...

Tips for Resizing and Reviving Divs with jQuery

I have recently ventured into the world of web development to assist a family member with their website. My knowledge and experience are limited, but I am facing an interesting challenge. I am trying to manipulate certain divs as users scroll down the page ...

The SetInterval function will continue to run within a web component even after the corresponding element has been removed from the

I am currently engaged in developing a straightforward application that coordinates multiple web components. Among these components, there is one that contains a setInterval function. Interestingly, the function continues to run even after the component it ...

Using jQuery to eliminate the 'disabled' attribute from CSS

After using the .val() method to enter data into a text box, I noticed that when trying to click "add", the button appears disabled. <input class="btn-primary action-submit" type="submit" value="Add" disabled=""> If I manually type in text, the dis ...

ClickAwayListener's callback function stops executing midway

I am currently utilizing Material-UI's ClickAwayListener in conjunction with react-router for my application. The issue I have come across involves the callback function of the ClickAwayListener being interrupted midway to allow a useEffect to run, on ...

Performing an ASync call to the GetData routine in MongoClient using NodeJS

Combining code snippets from https://www.w3schools.com/nodejs/nodejs_mongodb_find.asp and https://stackoverflow.com/questions/49982058/how-to-call-an-async-function#:~:text=Putting%20the%20async%20keyword%20before,a%20promise%20to%20be%20resolved. Upon ob ...

Conceal a table if it has no content

I am dealing with 2 tables that contain various data sets. img01 If both of my tables happen to be empty, I would prefer them to be hidden. img02 Is it feasible to implement this in Angular? If you have a solution for me, I would be eager to give it a ...

Oops! There seems to be an issue with the code: "TypeError: this

I am just starting out with Angular. Currently, I need to assign a method to my paginator.getRangeLabel (I want to use either a standard label or a suffixed one depending on certain conditions): this.paginator._intl.getRangeLabel = this.getLabel; The cod ...