typescript - 打字稿:需要帮助强制对函数响应进行严格输入
问题描述
我正在尝试构建一个类型,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
返回匹配的对象。
解决方案
的函数声明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)
推荐阅读
- python - rdd(row) remove duplicates within a partition using mapPartitions
- r - Fitting nls model with a categorical variable
- html - 调整 MUI CircularProgress
- javascript - 如何使用 PHP 使用聊天 API 在聊天中发送本地图像
- jquery - 单击一个 div 并再次单击另一个 div
- ios - 在 ipadOS 上覆盖 splitviewcontroller 的“主”视图
- firebase - TypeError:snapshot.forEach 不是 fetchData 的函数(C:\Users\HP\Desktop\stbot\index.js:152:18)
- c - 数组的C问题(我认为)|| 基本算术运算程序 N
- javascript - 是否可以创建一个刷新单个 vueJS 组件的方法?
- ios - 马上转到下一个 ViewController?