Typescript Disriminated Union所有对象成员的类型

时间:2017-05-29 18:14:52

标签: typescript

我有这样的事情:

export const MapDispatchToProps = {
    currentDateChanged,
    attendanceReceived,
    updateRecord,
    updateRecords,
};

export type ActionsType = typeof currentDateChanged | typeof attendanceReceived | typeof updateRecord | typeof updateRecords;

有没有办法定义区别的联合类型ActionsType而不重复MapDispatchToProps的属性?

2 个答案:

答案 0 :(得分:1)

我不知道是否有更清洁的方法,但技术上是可行的。

function f<T>(o: {[key: string]: T}): T {
  return undefined!;
}

const garbage = f(MapDispatchToProps);

export type ActionsType = typeof garbage;

浓缩(据我所知):

const garbage = (<T>(o: {[key: string]: T}): T => undefined!)(MapDispatchToProps);

export type ActionsType = typeof garbage;

答案 1 :(得分:0)

export type ActionsType = typeof MapDispatchToProps[keyof typeof MapDispatchToProps];

注意:仅当每个成员(MapDispatchToProps对象中的每个值)具有相同的属性标签(例如type)且不包含-重叠值。否则它将是一个联合会