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