Typescript:需要帮助在函数响应上强制严格键入吗
我正在尝试为Typescript:需要帮助在函数响应上强制严格键入吗,typescript,Typescript,我正在尝试为actionHandlers构建一个类型,该类型强制对象中的每个键和值为特定类型,并返回相同的对象:IPlatformState export const actionHandlers: ActionHandler<PlatformActionTypes, IPlatformState> = { [PlatformActionTypes.SET_PRODUCT]: (state: IPlatformState, action: ISetProductAction) =
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 const ActionHandler:ActionHandler={
[PlatformActionTypes.SET_PRODUCT]:(状态:IPlatformState,操作:ISetProductAction)=>{
返回{
…状态,产品:action.payload
}},
[PlatformActionTypes.SET_PRODUCT_GROUPS]:(状态:IPlatformState,操作:ISetProductGroupsAction)=>({
…状态,产品组:action.payload
})
}
export-type-ActionFunction=(状态:T,有效负载:any)=>T
导出类型ActionHandler={
[输入T]:操作功能
};
我的问题是我可以将ActionFunction
响应的新对象中的任何键更改为不在IPlatformState
中的内容,TS编译器不会抱怨
我基本上需要创建一个类型,确保只返回与
IPlatformState
匹配的对象。actionHandlers的函数声明应该能够强制执行有效负载的类型并返回,您不需要定义别名
至于对象和键的形状,你能用接口定义一切吗?下面是Typescript将强制执行类型的一些示例代码
interface-ithetypone{
[键:字符串]:()=>void
}
//所以所有这些都必须是key/string=>void类型
接口ITheOneWeUse扩展了IThetyPaOne{
帮助:()=>无效;
}
函数yourFunc(项:Itheonewuse):Itheonewuse{
退货项目
}
//还是泛型
函数otherFunc(i:T):T{
返回i
}
const示例={help:()=>console.log('hello')}
otherFunc(示例)
export type ActionFunction<T> = (state: T, payload: any) => T
export type ActionHandler<T extends PropertyKey, K> = {
[key in T]: ActionFunction<T>
};
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)