Trying to filter an array of number|undefined in TypeScript to only include numbers is not identified as an array of numbers

Below is the code snippet:

type TEntity = Array<{ size?: number }>

const someVar: TEntity =
    //@ts-ignore
    getFromSomewhere()

function isNumber(input: any): input is number {
    return !isNaN(Number(input))
}

const sizes1: number[] = someVar.map(entity => entity.size).filter(size => Number.isInteger(size));
const sizes2: number[] = someVar.map(entity => entity.size).filter(size => isNumber(size));

The expectation was to have sizes and sizes2 automatically typed as number[] post filtering, but this did not happen. Explicitly specifying types as : number[] also resulted in error. Even trying lodash's isNumber method didn't work.

Avoiding the non-null assertion operator (!) is crucial due to strict linting rules against it. How can the desired data type be obtained?

Access the TypeScript Playground here: Click here for the TypeScript Playground

Answer №1

To tackle this issue, utilizing (size) : size is number can be quite beneficial. Refer to this particular solution.

Take advantage of the following code snippets:
const sizes1: number[] = someVar.map(entity => entity.size).filter((size) : size is number => Number.isInteger(size));
const sizes2: number[] = someVar.map(entity => entity.size).filter((size) : size is number => isNumber(size));

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

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

Element not recognized: <my-company-form-extra> - have you properly registered this component?

I've been attempting to render a component using the is directive <template> <div> <v-tabs v-model="currentTab" fixed-tabs> <v-tab v-for="(item, i) in tabItems" :key="i">{{ item }} < ...

Handling a change event for a mat-datepicker in Angular 7 can be tricky, especially when its value is tied to an optional input parameter. Let's dive into how to

I've recently started working with angular development and encountered a challenge with a mat-datepicker. The value of the datepicker is connected to filterDate using [(ngModel)] as an @Input() parameter. I have implemented a handleChange event that e ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

A comprehensive guide on constructing a literal object in Typescript by combining an array with an object

Recently, I came across this Typescript code snippet: type SortedList = T[] & {_brand: "sorted" }; function binarySearch<T>(xs: SortedList<T>, x: T): boolean let low = 0; let high = xs.length - 1; while (high ...

What is the best way to explain a function that alters an object directly through reference?

I have a function that changes an object's properties directly: function addProperty(object, newValue) { object.bar = newValue; } Is there a way in TypeScript to indicate that the type of object is modified after calling the addProperty function? ...

How can I convert Typescript absolute paths to relative paths in Node.js?

Currently, I am converting TypeScript to ES5/CommonJS format. To specify a fixed root for import statements, I am utilizing TypeScript's tsconfig.json paths property. For instance, my path configuration might look like this: @example: './src/&ap ...

how to navigate to a different page programmatically upon selecting an option in the side menu

ionic start mySideMenu sidemenu --v2 After creating a sidemenu using the code above, I implemented some login-logout functionality by storing user details in a localStorage variable named "userDetails". When clicking on the logout option from the sideme ...

How to access nested JSON elements in Javascript without relying on the eval function

Below is a JSON that I am trying to access. { "orders": { "errorData": { "errors": { "error": [ { "code": "ERROR_01", "description": "API service is down" } ] } }, "status": " ...

How can models be aggregated in SQL by connecting them through other models?

I am working with a backend express API that utilizes sequelize. In my sequelize models, a Citizen is linked to a Street, which in turn is associated with a Town, and the Town is connected to a State. I can easily count the citizens on a specific Street by ...

add headers using a straightforward syntax

I'm attempting to append multiple header values. This is what I'm currently doing: options.headers.append('Content-Type', 'application/json'); options.headers.append('X-Requested-By', 'api-client'); ... ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Tips for acquiring the newest router in an angular environment

Is there a way to retrieve and store the URL of the latest router that the user has visited in local storage? Any suggestions would be greatly appreciated. Thank you! ...

Utilizing getServerSideProps and getInitialProps in Next.js to optimize page loading times

My page is not loading when I use getServerSideProps or getInitialProps. It keeps on loading without displaying the content, but everything works fine when I remove them. What could be wrong with my code here? HELP. ... interface Props { data: any; } co ...

Learn how to display data from the console onto an HTML page using Angular 2

I am working on a page with 2 tabs. One tab is for displaying active messages and the other one is for closed messages. If the data active value is true, the active messages section in HTML should be populated accordingly. If the data active is false, th ...

Before running any unit tests, I have to address all linting issues as required by ng test

Upon running ng test, the output I receive is as follows: > ng test 24 12 2019 14:20:07.854:WARN [karma]: No captured browser, open http://localhost:9876/ 24 12 2019 14:20:07.860:INFO [karma-server]: Karma v4.4.1 server started at http://0.0.0.0:9876/ ...

Configuration options for Path Aliases in TypeScript

In my Next.js project, I am utilizing TypeScript and have organized my files as follows: |-- tsconfig.json |-- components/ |---- Footer/ |------ Footer.tsx |------ Footer.module.sass My path aliases are defined as:     "paths": {       ...

Utilizing numerical values in useParams - A beginner's guide

Trying to access specific data from my json file using an ID, like "http://localhost:3001/pokemons/3", leads to a 404 error. All the data is visible at http://localhost:3001/pokemons. It seems that useParams doesn't want me to use id as a number - q ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...