Search code examples
typescripttypeslookuptsc

How to anger TSC with Lookup types


I want Typescript compiler (TSC) to get angry at me when I mistype signatures.

export class EventEmitter<EventTypes extends { [key: string]: any }> {
    subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, fn: <T extends EventTypes[Event]>(value: T) => any) {

    }
}

export class Data {
    name: string;
}

export class Experiment extends EventEmitter<{ "next": Data, "end": Data[] }> {

}

new Experiment().subscribe("end", (v: Date) => {});

As far as I understand it, tsc should be unhappy with (v: Date) because Date is not Data[]. How can I accomplish this?


Solution

  • I was over-complicating things. The solution is straight-forward.

    export class EventEmitter<EventTypes extends { [key: string]: any }> {
        subscribe<Event extends keyof EventTypes>(type: Event, fn: (value: EventTypes[Event]) => any) {
    
        }
    }
    

    Notice how the type parameter changed from keyof EventTypes to Event. That's the crux of it.