简体   繁体   English

TypeScript类型包含其他类型的键,但具有不同的值类型

[英]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.

相关问题 Typescript接口类型,带有可选的不同类型的键和strictNullChecks - Typescript interface type with optional keys of different types and strictNullChecks 如何在打字稿中使用不同类型的通用键键入对象 - How to type an object with generic keys of different types in typescript TypeScript通过其值类型缩小可索引类型的键 - TypeScript narrow down the keys of indexable type by its value types 在 Typescript 中,当数组包含不同的元素类型时,如何从数组类型中获取元素类型? - In Typescript how do you get an element type from an array type, when the array contains different element types? Typescript 联合类型到其他联合类型上的键 - Typescript union types to keys on other union type 替换 Typescript 类型中某些键上的类型 - Replace types on some keys in a Typescript type Map 根据 Typescript 中的键类型设置不同类型的值 - Map set different types of value depending on key type in Typescript 创建具有与 Enum 相同键的类型,但每个键具有不同的值 - Create a type with same keys as an Enum but each key has a different value 是否可以从另一种类型的 object 中创建一种类型的 object,具有相同的键名,但它们的值类型不同? - Is it possible to create a type of object from another type of object with the same keys names, but different types of values of them? 为 Typescript 中的字典的某些键指定不同的类型 - Specify a different type for some keys of a dictionary in Typescript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM