【问题标题】:Generics in TypeScript - Type is not assignable to type (missing the following properties)TypeScript 中的泛型 - 类型不可分配给类型(缺少以下属性)
【发布时间】: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


    【解决方案1】:

    嗯,你的减速器的状态是:

    ActionWithGeneric<T>[]
    

    但您正在尝试添加

    {text: action.data}
    

    到这个数组。

    {text: action.data} 不是ActionWithGeneric&lt;T&gt;,但action 是...

    你的意思是:

    switch (action.type) { 
        case "add": 
            return [...state, action]
        // ...
    

    ?

    【讨论】:

      猜你喜欢
      • 2019-06-22
      • 1970-01-01
      • 2019-06-04
      • 2018-09-19
      • 2017-12-05
      • 2021-01-05
      • 2021-06-24
      • 2018-07-06
      • 2019-08-03
      相关资源
      最近更新 更多