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
// a function to take either an iterator or an iterable, and return an iterable (for for..of)exportfunctioniterable<T>(iter: Iterator<T>|Iterable<T>): Iterable<T>{if(isIterator(iter)){//const iter2 = iter //<== returning iter2 instead works fine, iter2 is inferred to be Iterator<T>return{[Symbol.iterator](){returniter}// <== this is marked as an error, reports iter as `Iterator<T> | Iterable<T>` in spite of the guard}}if(isIterable(iter))returniter// works finethrownewError("provided argument neither iterable nor iterator")}// guardsexportfunctionisIterable<T>(iter: Iterable<T>|Iterator<T>): iter is Iterable<T>;exportfunctionisIterable(iter: any): iter is Iterable<any>{if(iter==null)returnfalseif(!(iter[Symbol.iterator]instanceofFunction))returnfalsereturntrue}exportfunctionisIterator<T>(iter: Iterable<T>|Iterator<T>): iter is Iterator<T>;exportfunctionisIterator(iter: any): iter is Iterator<any>{if(iter==null)returnfalsereturn(typeofiter.next==='function')}
I would expect iter to be allowed as a return value, since it has been guarded.
Actual behavior:
Only iter2 is allowed to be returned, if defined.
I wondered if this might have been due to iter being a var-scoped name, so I tried defining a const iter2 = iter at the top and then calling the guards on iter2, but that also didn't work.
Apologies for the terrible title, I'm not familiar enough with typing jargon yet to succinctly describe what I'm seeing. (and I'm willing to believe it's working as intended, but I'm not positive)
The text was updated successfully, but these errors were encountered:
exportfunctioniterable<T>(iter: Iterator<T>|Iterable<T>): Iterable<T>{if(isIterator(iter))return{[Symbol.iterator]: ()=>iter}// this too: if (isIterator(iter)) return { [Symbol.iterator]: function () { return iter }}if(isIterable(iter))returniterthrownewError("provided argument neither iterable nor iterator")}
The arrow/function expressions seems to infer the guarded type, even though the short-format method did not.
TypeScript Version: 2.0.2
Code
Possibly related: #10734 ?
Expected behavior:
I would expect iter to be allowed as a return value, since it has been guarded.
Actual behavior:
Only iter2 is allowed to be returned, if defined.
I wondered if this might have been due to
iter
being avar
-scoped name, so I tried defining aconst iter2 = iter
at the top and then calling the guards oniter2
, but that also didn't work.Apologies for the terrible title, I'm not familiar enough with typing jargon yet to succinctly describe what I'm seeing. (and I'm willing to believe it's working as intended, but I'm not positive)
The text was updated successfully, but these errors were encountered: