【问题标题】:Typescript and context, Type is not assignable打字稿和上下文,类型不可分配
【发布时间】:2021-05-11 19:57:03
【问题描述】:

您好,我正在学习 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;

还有这个 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,我不确定这种方式是否正确,但我的想法是创建一个结构类型我可以添加、编辑、删除、搜索和列出数据。

【问题讨论】:

    标签: reactjs typescript tsx


    【解决方案1】:

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

    补充说明:

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

    【讨论】:

    • addCat: (_)=>{} 是一个匹配上下文接口的空函数。它在上下文加载时被替换。它避免了必须检查 addCats 是否无处不在。你必须做 addCats && addCats(cat) 而不是你可以调用 addCats(cat)
    • 您还应该向 reducer 添加类型 - newline.co/@bespoyasov/…
    • 好的,谢谢兄弟!...另一个,如果我有另一个返回一个项目的函数,我应该在接口内部添加:selectCat: (cat: structCat) => void ???或者应该是 => structCat
    • return void (=>void) 应该只在函数不返回任何东西时使用。如果您的函数返回一个值,它应该反映返回类型 ()=>structCat 或 ()=>boolean 等。如果您使用 VSCode,请安装 typescript 扩展 - 如果您不指定类型,则可以将鼠标悬停在变量上,= >,函数名和 VSCode 会告诉你类型应该是什么。
    猜你喜欢
    • 2021-10-11
    • 2020-06-29
    • 2016-10-25
    • 2019-09-25
    • 1970-01-01
    • 2022-08-14
    • 2022-01-21
    • 2021-08-19
    • 1970-01-01
    相关资源
    最近更新 更多