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
typeListeners<KextendskeyofEVENTS,EVENTS>=Array<(data: EVENTS[K])=>void>exportdefaultclassEventManager<EVENTSextends{}>{privatelisteners: {[KinkeyofEVENTS]?: Listeners<K,EVENTS>}={}privategetListeners<KextendskeyofEVENTS>(name: K): Array<(data: EVENTS[K])=>void>{// It works if we help the compiler with... the type it has for real// let listeners: Array<(data: EVENTS[K]) => void> | undefined = this.listeners[name]letlisteners=this.listeners[name]if(!listeners){constnewArray=this.listeners[name]=[]returnnewArray}else{// Type guard fails! Nothing was refinedreturnlisteners}}}
Expected behavior:
The type is correctly inferred and the type guard does something
Same underlying issue as #22137. narrowing does not really work on generic types. in cases like these, you want the narrowing operation (if (!listeners) to be translated into a type operator applies to the type of listeners). #22348 takes a stab at fixing it.
Automatically closing this issue for housekeeping purposes. The issue labels indicate that it is unactionable at the moment or has already been addressed.
TypeScript Version: 2.9.2 and next@2018-08-24
Search Terms:
mapped type inference type guard
Code
Expected behavior:
The type is correctly inferred and the type guard does something
Playground Link:
https://www.typescriptlang.org/play/#src=type%20Listeners%3CK%20extends%20keyof%20EVENTS%2C%20EVENTS%3E%20%3D%20Array%3C(data%3A%20EVENTS%5BK%5D)%20%3D%3E%20void%3E%0D%0A%0D%0Aexport%20default%20class%20EventManager%3CEVENTS%20extends%20%7B%7D%3E%20%7B%0D%0A%0D%0A%20%20private%20listeners%3A%20%7B%20%5BK%20in%20keyof%20EVENTS%5D%3F%3A%20Listeners%3CK%2C%20EVENTS%3E%20%7D%20%3D%20%7B%7D%0D%0A%0D%0A%20%20private%20getListeners%3CK%20extends%20keyof%20EVENTS%3E(name%3A%20K)%3A%20Array%3C(data%3A%20EVENTS%5BK%5D)%20%3D%3E%20void%3E%20%7B%0D%0A%20%20%20%20%2F%2F%20It%20works%20if%20we%20help%20the%20compiler%0D%0A%20%20%20%20%2F%2F%20let%20listeners%3A%20Array%3C(data%3A%20EVENTS%5BK%5D)%20%3D%3E%20void%3E%20%7C%20undefined%20%3D%20this.listeners%5Bname%5D%0D%0A%0D%0A%20%20%20%20%2F%2F%20Doesn't%20work%0D%0A%20%20%20%20let%20listeners%20%3D%20this.listeners%5Bname%5D%0D%0A%0D%0A%20%20%20%20if%20(!listeners)%20%7B%0D%0A%20%20%20%20%20%20%20%20const%20newArray%20%3D%20this.listeners%5Bname%5D%20%3D%20%5B%5D%0D%0A%20%20%20%20%20%20%20%20return%20newArray%0D%0A%20%20%20%20%7D%0D%0A%20%20%20%20else%20%7B%0D%0A%20%20%20%20%20%20%20%20%2F%2F%20Type%20guard%20fails!%0D%0A%20%20%20%20%20%20%20%20return%20listeners%0D%0A%20%20%20%20%7D%0D%0A%20%20%7D%0D%0A%7D
The text was updated successfully, but these errors were encountered: