首页 > 解决方案 > 打字稿:需要帮助强制对函数响应进行严格输入

问题描述

我正在尝试构建一个类型,actionHandlers它强制对象中的每个键和值都是某种类型并返回相同的对象:IPlatformState.

export const actionHandlers: ActionHandler<PlatformActionTypes, IPlatformState> = {
  [PlatformActionTypes.SET_PRODUCT]: (state: IPlatformState, action: ISetProductAction) => {
    return {
    ...state, product: action.payload
  }},

  [PlatformActionTypes.SET_PRODUCT_GROUPS]: (state: IPlatformState, action: ISetProductGroupsAction) => ({
    ...state, productGroups: action.payload
  })
}
export type ActionFunction<T> = (state: T, payload: any) => T

export type ActionHandler<T extends PropertyKey, K> = {
  [key in T]: ActionFunction<T>
};

我的问题是我可以将ActionFunction响应的新对象中的任何键更改为不存在的内容,IPlatformState并且 TS 编译器不会抱怨。

我基本上需要创建一种类型,以确保只能IPlatformState返回匹配的对象。

标签: typescript

解决方案


的函数声明actionHandlers应该能够强制执行有效负载的类型并返回,您不需要定义别名。

至于对象和键的形状,你能用接口来定义一切吗?这是一些示例代码,其中 Typescript Playground 将强制执行类型链接

interface ITheTypeOne {
    [key: string]: () => void
}

// So all of these must be of type key/string => void
interface ITheOneWeUse extends ITheTypeOne {
    help: () => void;
}

function yourFunc(item: ITheOneWeUse): ITheOneWeUse {
    return item
}

//or with generics

function otherFunc<T>(i: T): T {
    return i
}

const example = { help: () => console.log('hello') }

otherFunc<ITheOneWeUse>(example)

推荐阅读