简体   繁体   中英

create a union type in typescript with methods of a class

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM