你好,我正在学习typescript,我有一个Type错误,这是组件catcontext.tsx:
import { createContext } from "react";
interface structCat {
id: number,
idParent: number,
description: string
};
const CatContext = createContext<structCat | null>(null);
export default CatContext;
和这个全局状态.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"
}
]
所以,我试图使用contextapi和typescript创建项目,所以类型context应该是类型structData.json,我不确定这种方式是否正确,但我的想法是创建一个结构类型,我可以添加、编辑、删除、搜索和列出数据。
{ 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: (_)=>{}
})