[英]TypeScript type contains keys of another type but has different value types
If I have this const in which the values are all functions: 如果我有这个const,其中所有值都是函数:
export const staffingReducers = {
calendar: calendarReducer,
navigation: navigationReducer,
shifts: shiftsReducer,
};
I have an interface defined as such: 我有这样定义的接口:
export interface StaffingState {
calendar: CalendarState;
navigation: NavigationState;
shifts: ShiftState;
selectedId: number;
}
I would like to enforce that my staffingReducers have all the same keys as the StaffingState. 我想强制要求我的staffingReducers具有与StaffingState相同的键。 Is this possible? 这可能吗?
Sure thing: 当然可以:
const staffingReducers: { [K in keyof StaffingState]: Function } = {
calendar: calendarReducer,
navigation: navigationReducer,
shifts: shiftsReducer,
};
With your current code it will result in an error because staffingReducers
doesn't have a property for selectedId
. 使用您当前的代码,将导致错误,因为staffingReducers
没有selectedId
的属性。
You can find more info here: Mapped Types 您可以在此处找到更多信息: 映射类型
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.