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

Time:04-12

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.

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

CodePudding user response:

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