Search code examples
typescriptgenericstypescript-genericsmapped-types

Generic class use type as value, or pass property as index for indexed type


I have a class like this

interface Events {
    ready: [Date];
    start: [];
    stop: [];
}

export abstract class Event<Name extends keyof Events> {
    public abstract readonly name: Name;

    public someFunction(args: Events[Name]) {
        callSomeFunction(this.name, args);
    }
}

And I'm asking if some way I could remove either the generic type or the name property to avoid repetition in my code ?


Solution

  • Okay I found something that works :

    export abstract class Event {
        public abstract readonly name: keyof Events;
    
        public someFunction(args: Events[this['name']]) {
            callSomeFunction(this.name, args);
        }
    }
    

    So I can do this :

    class ReadyEvent extends Event {
        name = 'ready';
    }
    

    Without putting multiple times 'ready' ^^