【发布时间】:2021-10-04 10:21:59
【问题描述】:
我创建了以下interface、type 和function。
interface ActionWithGeneric<T> {
type: 'add' | 'remove';
data: T;
}
type StateWithGeneric<T> = Array<ActionWithGeneric<T>>
const TodoReducerGeneric : <T,> (state: StateWithGeneric<T>, action: ActionWithGeneric<T>) => StateWithGeneric<T> = (state, action) => {
switch (action.type) {
case "add":
return [...state, {text: action.data}]
case "remove":
return state.filter(a => action.data !== a.data)
default:
return state
}
}
接下来,我尝试在我的 React 组件中按如下方式使用它:
const TextField : React.FC<Props> = ({text}) => {
const [data, dispatchData] = useReducer(TodoReducerGeneric, [])
return (
<div>{data}</div>
)
}
我的TodoReducerGeneric 收到以下错误:
Type '<T>(state: StateWithGeneric<T>, action: ActionWithGeneric<T>) => (ActionWithGeneric<T> | { text: T; })[]' is not assignable to type '<T>(state: StateWithGeneric<T>, action: ActionWithGeneric<T>) => StateWithGeneric<T>'.
Type '(ActionWithGeneric<T> | { text: T; })[]' is not assignable to type 'StateWithGeneric<T>'.
Type 'ActionWithGeneric<T> | { text: T; }' is not assignable to type 'ActionWithGeneric<T>'.
Type '{ text: T; }' is missing the following properties from type 'ActionWithGeneric<T>': type, data
我知道存在类型不匹配,但我很难理解错误消息中 {text : T;} 的来源或如何修复它。
【问题讨论】:
标签: reactjs typescript generics typescript-generics react-typescript