Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

TypeScript: Filtering an array of number|undefined to include only numbers is not recognized as array of numbers

This is my code:

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));

I expected sizes and sizes2 to be automatically of type number[] after filtering them, but they weren’t. Also specifying types as : number[] also is a mistake. I also tried lodash’s isNumber method, but still no luck.

I don’t want to use non-null assertion operator (!) as I’m logically filtering everything, and I have linters to prevent usage of non-null assertions.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I get the correct type I want?

Here is the link to the TS PlayGround: https://www.typescriptlang.org/play?#code/C4TwDgpgBAKgogO2AS1FAvFAggJxwQxAB4BvKAZ2QC8IB+ALigQFcBbAIwhygF8A+AFACAxgHsE5YBVGsIANXw5G8JKhAYBULVAD0OgALByAWmQBzBKJwRN2sxGAAxHDIDKMiAHcAFlwgAKAEohADNmBGEUcShkcgA5Nk4cf2QEMGZgRnwEEEDGVPSpWKZErigSWy1rYGYcBCgAQli4-Dj-BI4uFLSMwOCeITEJKUoacgBGRhZOnABtAF0MaVkFHAA6VnwwfwhVNHQ+KF2UUDXRiEC1kOQAG2Au84xDjqS12IBJJAh7ZPO+gG4ROJJBRqBByAAmKalOaLTDkDyrDZbHZ7dQHI5os5gy7XO4PMFPGLxGH+P6Bf5AA

>Solution :

Using (size) : size is number will help you in this case. See this answer.

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading