Reactjs 类型脚本和上下文,类型不可分配

Reactjs 类型脚本和上下文,类型不可分配,reactjs,typescript,tsx,Reactjs,Typescript,Tsx,您好,我正在学习typescript,我遇到一个类型错误,这是组件catcontext.tsx: import { createContext } from "react"; interface structCat { id: number, idParent: number, description: string }; const CatContext = createContext<structCat | null>(nu

您好,我正在学习typescript,我遇到一个类型错误,这是组件catcontext.tsx:

import { createContext } from "react";

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

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

export default CatContext;
Data.json结构类似于:

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

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

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

补充说明:

  • cat应为-structCat类型
  • CAT应该是structCat的类型数组
  • 如果可以避免默认上下文,或者默认上下文不是用于此目的的有效值,则默认上下文不应为null
  • AddCat应该是AddCat-最好只大写react组件名称的第一个字母
接口上下文{
猫:structCat[];
addCat:(cat:structCat)=>void;
}
createContext({
猫:[],
addCat:()=>{}
})

谢谢兄弟!!!!()的意思是什么???in()=>{addCat:()=>{}是一个与上下文接口匹配的空函数。它在加载上下文时被替换。它避免了检查addCat是否无处不在。您必须执行addCat&&addCat(cat)操作,而只需调用addCat(cat)你还应该向你的减速机添加类型-好的,谢谢兄弟!…另一个,如果我有另一个返回一个项目的函数,我应该添加内部接口,比如:selectCat:(cat:structCat)=>void???或者应该是=>structCatok我明白了!谢谢兄弟!!
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
[
    {
        "id": 1,
        "idParent": null,
        "description": "main"
    },
    {
        "id": 2,
        "idParent": 1,
        "description": "name 1"
    }
]
interface ICatContext {
 cats: structCat[];
 addCat: (cat: structCat) => void;
}

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