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