繁体   English   中英

使用类的方法在打字稿中创建联合类型

[英]create a union type in typescript with methods of a class

我正在查看一些旧代码,它们已将所有redux reducer创建为类的实例方法:

@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.

我通常将它们创建为单独的函数

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

然后创建一个联合:

type MyActions = add | remove;

我可以以某种方式创建类实例方法的并集吗?

如果要keyof所有类型的键,可以使用keyof

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

如果该类还具有不是方法的公共字段,并且您想过滤掉这些公共字段,则可以使用条件类型:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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