![](/img/trans.png)
[英]How to prevent an overloaded function from being called with the wrong argument types
[英]How to extract the types of argument from a function that was passed as argument?
我有我想包裝在另一個函數中的函數,我的問題是我似乎無法找到一種方法來提取baseReducer
的參數並將它們分配給返回的函數。
也可以我提取類型參數的baseReducer
,並把它們作為類型withLoadingState
參數?
const START = 'START'
const SUCCESS = 'SUCCESS'
const ERROR = 'ERROR'
type Start = { type: typeof START }
type Success = { type: typeof SUCCESS; payload: string[] }
type Error = { type: typeof ERROR }
type State = {
results: string[]
loading: boolean
error: boolean
}
export const initialState: State = {
results: [],
loading: false,
error: false,
}
type ActionTypes = Start | Success | Error
const reducer = (state = initialState, action: ActionTypes) => {
switch (action.type) {
default:
return state
}
}
// I would also like to use the type of baseReducer action as the type
// of the parameters of withLoadingStates
const withLoadingStates = () => {
// how to extract the types of state and action from base reducer
// and assign them to state and action of the returned function
return baseReducer => (state, action) => {
const nextState = state // manipulate state but keep the same type
return baseReducer(nextState, action)
}
}
const wrappedReducer = withLoadingStates()(reducer)
您可以添加一些類型參數來捕獲狀態類型和操作類型:
const withLoadingStates = () => {
// how to extract the types of state and action from base reducer
// and assign them to state and action of the returned function
return <S, A>(baseReducer: (state: S, action: A) => S) => (state: S, action: A) => {
const nextState = state // manipulate state but keep the same type
return baseReducer(nextState, action)
}
}
baseReducer
( (state: S, action: A) => S
) 的類型也將確保 reduce 具有適當的類型
我這就是你想要做的?
const START = 'START';
const SUCCESS = 'SUCCESS';
const ERROR = 'ERROR';
type Start = { type: typeof START };
type Success = { type: typeof SUCCESS; payload: string[] };
type Error = { type: typeof ERROR };
type State = {
results: string[];
loading: boolean;
error: boolean;
};
export const initialState: State = {
results: [],
loading: false,
error: false
};
type ActionTypes = Start | Success | Error;
const reducer = (state = initialState, action: ActionTypes) => {
switch (action.type) {
default:
return state;
}
};
type FunctionParams<F extends (...args: any[]) => any> = F extends (...args: infer P) => any ? P : any[];
const withLoadingStates = () => {
return <F extends (...args: any[]) => any>(baseReducer: F) => (...[state, action]: FunctionParams<F>) => {
const nextState = state; // manipulate state but keep the same type
return baseReducer(nextState, action);
};
};
const wrappedReducer = withLoadingStates()(reducer);
// mouseover > const wrappedReducer: (state: State, action: ActionTypes) => any;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.