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

时间:2019-01-08 12:28:07

标签: typescript ngredux

我正在查看一些旧代码,它们已经创建了所有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;

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

1 个答案:

答案 0 :(得分:1)

如果您想要所有类型的键的并集,则可以使用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"
相关问题