打字稿和上下文,类型不可分配

时间:2021-05-11 19:57:03

标签: reactjs typescript tsx

你好,我正在学习打字稿,我遇到了类型错误,这是组件 catcontext.tsx:

import { createContext } from "react";

interface structCat {
    id: number,
    idParent: number,
    description: string    
};

const CatContext = createContext<structCat | null>(null);

export default CatContext;

还有这个 globalstate.tsx:

import CatContext from './CatContext';
import CatReducers from './CatReducers';
import { useReducer } from 'react';
import Data from '../../../Data/Data.json';

const initialState = {
    cats: Data,
}

function GlobalState(props: any){

    const [ state, dispatch ] = useReducer(CatReducers, initialState);


const AddCat = (cat: any) => {
    dispatch({
        type: ADD_CAT,
        payload: cat
    });
}
    return(
        <CatContext.Provider
            value={{
                cats: state.cats,
                AddCat
            }}

        >
            {props.children}
        </CatContext.Provider>
    )

}

export default GlobalState;

这是错误:

Type '{ cats: any; AddCat: (cat: any) => void; }' is not assignable to type 'structCat'.
  Object literal may only specify known properties, and 'cats' does not exist in type 'structCat'.  TS2322

Data.json 结构类似于:

[
    {
        "id": 1,
        "idParent": null,
        "description": "main"
    },
    {
        "id": 2,
        "idParent": 1,
        "description": "name 1"
    }
]

所以,我正在尝试使用上下文 api 和 typescript 创建项目,所以类型上下文应该是类型 struct Data.json,我不确定这种方式是否正确,但我的想法是创建一个结构类型我可以添加、编辑、删除、搜索和列出数据。

1 个答案:

答案 0 :(得分:1)

{ cats: any; AddCat: (cat: any) => void; } 不等于 { id: number, idParent: number, description: string }

附加说明:

  • cat 应该是类型 - structCat
  • cats 应该是类型 - structCat 数组
  • 如果可以避免或不是真正有效的值,则默认上下文不应为 null。
  • AddCat 应该是 addCat - 最好只将 React 组件名称的第一个字母大写
interface ICatContext {
 cats: structCat[];
 addCat: (cat: structCat) => void;
}

createContext<ICatContext>({
 cats: [],
 addCat: (_)=>{}
})
相关问题