TypeScript Version: 3.6.0-dev.20190720
Search Terms: type narrowing undefined generics early return
Code
typeBaseEvents={[event: string]: Array<any>};typeCbs<AextendsBaseEvents>={[PinkeyofA]: Array<(...args: A[P])=>boolean|Promise<boolean>>|undefined;}exportclassEvents<TextendsBaseEvents>{privatecbs: Cbs<T>={}asany;asyncemit<PextendskeyofT>(event: P, ...args: T[P]){constarr=this.cbs[event];// typeof arr = ((...args: T[P]) => boolean | Promise<boolean>)[] | undefinedtypeNonNullArr=NonNullable<typeofarr>;// ((...args: T[P]) => boolean | Promise<boolean>)[]if(typeofarr==='undefined'){return;}// typeof arr should now be ((...args: T[P]) => boolean | Promise<boolean>)[]constnonNullArr: NonNullArr=arr;// TS2322: Type '((...args: T[P]) => boolean | Promise<boolean>)[] | undefined' is not assignable to type 'NonNullable<Cbs<T>[P]>'.// Type 'undefined' is not assignable to type 'NonNullable<Cbs<T>[P]>'.for(constcbofarr){// TS2488: Type 'Cbs<T>[P]' must have a '[Symbol.iterator]()' method that returns an iterator.}for(constcb2ofnonNullArr){// No error}}}Expected behavior: Compiles without errors.
Actual behavior: Several errors relating to arr not narrowing out the undefined portion of the argument:
Error:(14, 15) TS2322: Type '((...args: T[P]) => boolean | Promise<boolean>)[] | undefined' is not assignable to type 'NonNullable<Cbs<T>[P]>'.
Type 'undefined' is not assignable to type 'NonNullable<Cbs<T>[P]>'.
Error:(16, 26) TS2488: Type 'Cbs<T>[P]' must have a '[Symbol.iterator]()' method that returns an iterator.
Playground Link
Related Issues:
#1726 (closed by design, this is different because we can assume any array is not undefined)
#31456 (this example has a constraint)
TypeScript Version: 3.6.0-dev.20190720
Search Terms: type narrowing undefined generics early return
Code
Expected behavior: Compiles without errors.
Actual behavior: Several errors relating to arr not narrowing out the
undefinedportion of the argument:Playground Link
Related Issues:
#1726 (closed by design, this is different because we can assume any array is not undefined)
#31456 (this example has a constraint)