The 'split' property is not present on the 'string | number | {}' type

Just starting out with Typescript and I've encountered an error stating that the split method does not exist on type number. I've tried narrowing down the type by checking the value's type, but so far it hasn't been successful. Below is the code snippet:

file.ts

interface AIObject {
  CLARITY_CODE?: string | {};
  CARAT?: number | {};
  SHAPE_CODE?: string | {};
}

const numericKeys = [
    "CARAT",
  ];

const arrObj: AIObject[] = [
  {
    CLARITY_CODE: "DE",
    CARAT: 5,
    SHAPE_CODE: "SI",
  },
];

arrObj.map((obj: AIObject) => {
  let ov = Object.keys(obj);
  ov.forEach((val) => {
    if (typeof obj[val as keyof AIObject] === "string") {
      const check = obj[val as keyof AIObject]?.split("-");
      //     console.log(check);
      if (check.length === 2) {
        if (numericKeys.includes(val)) {
          obj[val as keyof AIObject] = { $gte: check[1], $lte: check[0] };
        } else {
          obj[val as keyof AIObject] = [...check];
        }
      }
    }
  });
});

Answer №1

The reason behind your issue is that the typeof check on obj[val] does not function as a type guard as you intended. The problem arises because there is no assurance that the value of obj[val] obtained previously will remain the same when used later. Consider a scenario where an object has a custom getter for val that returns a value of varied types: since the getter is called twice, the compiler is unable to ascertain that it will retain the same type, possibly being a string, number, or object.

A potential solution is to store the value of obj[val] in a variable, which will allow your type guard to function as anticipated. You can refer to this Example for better understanding.

Alternatively, you could cast the value to a string before invoking .split(). Knowing that it will be a string, this can help the type system accept it without any issues.

Answer №2

In TypeScript, it's important to specify the data type when using conditionals like the if statement. This technique is called Type Assertion.

By using (obj[val as keyof AIObject] as string), you can force the value to be treated as a string, ensuring that your condition functions correctly.

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

Supervising the organization of HTML sections for an offline web application

Currently, I am developing an offline HTML5 application that involves a significant amount of DOM manipulation through the creation of HTML strings within JavaScript functions. For example: var html=''; html+='<div class="main">&apos ...

Is there a way to use nightwatch.js to scan an entire page for broken images?

Hi there, I'm currently working on creating a test to ensure that all images are loaded on a webpage with just one single test. I assumed this would be a straightforward task that many people have already done before, but unfortunately, I haven' ...

Filtering multiple rows in a table using Javascript

I'm currently working on creating a filter that can filter based on multiple inputs, with each input filtering in a separate column. Here is the JavaScript & code I am using: function myFunction(column, input) { var filter, table, tr, td, i, t ...

Guide on exporting member formModule in angular

After compiling my code in cmd, an error message is displayed: ERROR in src/app/app.module.ts(3,10): error TS2305: Module '"C:/Users/Amir_JKO/my-first-app/node_modules/@angular/forms/forms"' does not have an exported member 'formModul ...

Displaying nested object properties in HTML through iteration

What is the correct way to access them if item.NestObj.textpropertyVal is showing incorrect? success: function(data){ var html = ""; $.each(data.mainOutterObj, function (index, item) { html += "<ul&g ...

Vue Router is failing to match a URL that contains numerous dynamic parameters

I've been working on adding a nested url to my routes and have encountered an issue with the last route in my code. Every other route seems to be functioning properly. I attempted to nest the urls using the children property, but it wasn't succe ...

An unexpected error occurred in the Angular unit and integration tests, throwing off the script

I seem to be facing a recurring issue while running unit/integration tests for my Angular project using Karma. The tests have a 50:50 success/failure rate, working fine on my machine but failing consistently on our build server, making the process quite un ...

Creating objects based on interfaces

After looking at this straightforward code: interface int1 { aa: string, bb: number, } const obj1:int1 = {} //#1 function fun(param_obj:int1) { //#2 } I am curious as to why the compiler throws an error: Type '{}' is missing the fol ...

The type 'any' cannot be assigned to the type 'never' as a parameter

const [files, setFiles] = useState([]) const handleChange = (event: any) => { setFiles.push(event.target.files[0].name) return (<div> {files.map((file: any) => ( <p>Hello!</p> ))} </ ...

Prevent draggable canvas elements from overlapping using jQuery

I'm currently working on a project where I need to make three canvas elements draggable while preventing them from overlapping each other. After researching similar issues, I came across the "jquery-ui-draggable-collision" library. Here is the code I ...

The error message "Property 'zip' is not available on the 'Observable' type in Angular 6" indicates that the zip property is not recognized by

I've been working with Angular 6 and I've also looked into using pipes, but I couldn't find the correct syntax for writing a zip function and importing it properly. Error: Property 'zip' does not exist on type 'typeof Observ ...

Facing a node.js installation issue on Windows 10 while using Visual Studio Code (VS

Issue encountered while trying to execute "DownloadString" with one argument: Unable to establish a secure connection due to SSL/TLS channel creation failure. At line:1 char:1 + iex ((New-Object System.Net.WebClient).DownloadString('https ...

Finding the arithmetic operator and then assigning both the operator and its index to a globally accessible variable can be accomplished through a

Hello, I am currently learning web development and as a beginner project, I am working on creating a calculator in React. My goal is to have the selected arithmetic operation ("+", "/", "-", or "X") executed when the user clicks "=". To achieve this, I s ...

What is the method to retrieve the class name of an element when the div is created as '<div id 'one' class="element one"></div>'?

I have three elements named one, two, and three, declared as seen below: <div id =container> <div id 'one' class="element one"></div> <div id 'two' class="element two"></div> < ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

Angular 7: Polyfill required for npm package to support 'Class'

I am encountering an issue where my Angular 7-based app is not functioning in Internet Explorer 11. The npm package I am using begins in index.js: class PackageClass { // code } While the app works as intended in other browsers, it fails to open in ...

Experiencing issues with transferring JSON response from Axios to a data object causing errors

When I try to assign a JSON response to an empty data object to display search results, I encounter a typeerror: arr.slice is not a function error. However, if I directly add the JSON to the "schools" data object, the error does not occur. It seems like th ...

Ways to send distinct values to updateMany $set in mongodb

I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user. Below is the code snippet that I am working with: func ...

Make sure to implement validations prior to sending back the observable in Angular

Each time the button is clicked and if the modelform is invalid, a notification message should be returned instead of proceeding to create a user (createUser). The process should only proceed with this.accountService.create if there are no form validation ...

What are some methods to boost productivity during web scraping?

Currently, I have a node script dedicated to scraping information from various websites. As I aim to optimize the efficiency of this script, I am faced with the challenge that Node.js operates on a single-threaded runtime by default. However, behind the sc ...