You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
functionisNumber(x: any): x is number{returntypeof(x)==="number";}letnumbersOrStrings: (number|string)[]=[1,2,3,4];if(numbersOrStrings.every(isNumber)){let_numbers: number[]=numbersOrStrings;// ...}
Expected behavior:
When every member of numberOfStrings matches the isNumber type guard, the whole array should be inferred to be numberOfStrings: number[]; so, the above code should compile without error.
Actual behavior:
The above fails to compile, with the following error:
error TS2322: Type '(string | number)[]' is not assignable to type 'number[]'.
This issue is similar to #7657, and it can be solved by adding something like the following to lib.d.ts:
interfaceArray<T>{every<UextendsT>(pred: (a: T)=>a is U): this is U[];}
(or, the above can be added locally to a project as a temporary workaround)
It's not the same, though. filter creates a new array, every doesn't. Assigning (string | number)[] to a number[] is unsafe, because a string can be pushed at any moment.
Reacted by Aluan Haddad, Simon Warta and Marouane Fazouane
Activity
vkurchatkin commentedon Apr 1, 2017
It's not the same, though.
filtercreates a new array,everydoesn't. Assigning(string | number)[]to anumber[]is unsafe, because a string can be pushed at any moment.kylewlacy commentedon Apr 2, 2017
Vladimir Kurchatkin (@vkurchatkin) Would adding the above declaration for
ReadonlyArray<T>be safe, then?vkurchatkin commentedon Apr 3, 2017
Kyle Lacy (@kylewlacy) yes, I think so
Added overload to ReadonlyArray.prototype.every to make it a type gua…
Added overload to ReadonlyArray.prototype.every to make it a type gua…
Added overload to ReadonlyArray.prototype.every to make it a type gua…
Added overload to ReadonlyArray.prototype.every to make it a type gua…
Added overload to ReadonlyArray.prototype.every to make it a type gua…
Added overload to ReadonlyArray.prototype.every to make it a type gua…
mhegazy commentedon May 2, 2018
related to #5101
mhegazy commentedon May 2, 2018
#16069 now tracks inferring the type guard automatically.