TypeScript类型包含另一种类型的键,但具有不同的值类型

时间:2017-06-12 16:03:08

标签: typescript

如果我有这个值,其中值都是函数:

export const staffingReducers = {
    calendar: calendarReducer,
    navigation: navigationReducer,
    shifts: shiftsReducer,
};

我有一个如此定义的接口:

export interface StaffingState {
    calendar: CalendarState;
    navigation: NavigationState;
    shifts: ShiftState;
    selectedId: number;
}

我想强制我的staffingReducers拥有与StaffingState相同的所有键。这可能吗?

1 个答案:

答案 0 :(得分:4)

当然可以:

const staffingReducers: { [K in keyof StaffingState]: Function } = {
    calendar: calendarReducer,
    navigation: navigationReducer,
    shifts: shiftsReducer,
};

使用您当前的代码会导致错误,因为staffingReducers没有selectedId的属性。

您可以在此处找到更多信息:Mapped Types