Skip to content

SUGGESTION: Assert return type is not undefined or null #15100

Description

TypeScript Version: 2.3.0-dev.20170407

Code
Paste in the following code and scroll to the final two lines:

exporttypeSubscription={dispose: ()=>void};exporttypeSubscriberCallbacks<Events>={[eventinkeyofEvents]?: Function;};exportclassSubscribers<EventsextendsSubscriberCallbacks<Events>>{privatesubscribers: Set<Events>=newSet<Events>();publicadd(events: Events): Subscription{this.subscribers.add(events);returnthis.createDisposer(events);}publicgetNotifier<EventNameextendskeyofEvents>(eventName: EventName): Events[EventName]{return(...args: any[])=>this.notify(eventName, ...args);}privatenotify<EventNameextendskeyofEvents>(eventName: EventName, ...args: any[]){this.getReleventSubscribers(eventName).forEach((callback: Function)=>callback(...args));}privatecreateDisposer(events: Events){return{dispose: ()=>this.subscribers.delete(events)};}privategetReleventSubscribers(eventName: keyofEvents): Array<Events[keyofEvents]>{returnArray.from(this.subscribers).map(events=>events[eventName]).filter(callback=>typeofcallback!=='undefined');}}interfaceTestEventsextendsSubscriberCallbacks<TestEvents>{foo?: (bar: number)=>void,baz?: (qux: string)=>void,}lettestEventSubScribers=newSubscribers<TestEvents>();testEventSubScribers.add({foo: (bar: number)=>{console.log(bar);},});testEventSubScribers.add({foo: (bar: number)=>{console.log(bar+'hi');},baz: (qux: string)=>{console.log(qux+'hi');},});testEventSubScribers.getNotifier('foo')(2);testEventSubScribers.getNotifier('baz')('lala');

To remove the errors I need to assert that the result of the getNotifier call is not undefined.

testEventSubScribers.getNotifier('foo')!(2);testEventSubScribers.getNotifier('baz')!('lala');

Desired behavior:

It'd be nice if I could declare getNotifier as follows (note the final !):

exportclassSubscribers<EventsextendsSubscriberCallbacks<Events>>{publicgetNotifier<EventNameextendskeyofEvents>(eventName: EventName): Events[EventName]!{return(...args: any[])=>this.notify(eventName, ...args);}}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions