create a union type in typescript with methods of a class

741 views Asked by At

I am looking at some legacy code and they have created all the redux reducers as instance methods of a class:

@Injectable()
export class PeopleActions {
    constructor(private ngRedux: NgRedux<any>) {}

    add() {
      this.ngRedux.dispatch({ADD, payload: {foo: 'bar;});
    }

    remove() {
      this.ngRedux.dispatch({Remove, payload: {foo: 'bar;});
    }
    // etc.

I would normally create these as sepreate functions

export function add { // etc.}
export function remove { // etc.}

And then create a union:

type MyActions = add | remove;

Can I somehow create a union of the class instance methods?

1

There are 1 answers

1
Titian Cernicova-Dragomir On BEST ANSWER

If you want a union of all keys in the type you can use keyof

type MyActions = keyof PeopleActions; // "add" | "remove"

If the class also has public fields that are not methods and you want to filter those out you can use a conditional type:

type ExtractFunctionKeys<T> = { [P in keyof T]-?: T[P] extends Function ? P : never}[keyof T]
type MyActions = ExtractFunctionKeys<PeopleActions>; // "add" | "remove"