我正在try 构建一个项目,但类型判断显示以下错误:

Type error: Type 'OmitWithTag<typeof import("....calculator/page"), "metadata" | "default" | "config" | "generateStaticParams" | "revalidate" | ... 6 more ... | "generateMetadata", "">' does not satisfy the constraint '{ [x: string]: never; }'. Property 'ActiveTabContext' is incompatible with index signature. Type 'Context<ActiveTab>' is not assignable to type 'never'.

创建上下文代码:

type ActiveTab = [string, Dispatch<SetStateAction<string>>]
type SelectValues = [IApiCostsState[], Dispatch<SetStateAction<IApiCostsState[]>>]
type SumState = [number, Dispatch<SetStateAction<number>>]
type HelperState = [Helper, Dispatch<SetStateAction<Helper>>]

export const ActiveTabContext = createContext<ActiveTab>(['', () => { }]) as Context<ActiveTab>;
export const SelectValuesContext = createContext<SelectValues>([setInitial(Object.keys(_apiCostsMock)[0]), () => { }]);
export const TotalSumContext = createContext<SumState>([0, () => { }]);
export const HelperContext = createContext<HelperState>([{index:-1}, () => { }]);
export const WindowWidthContext = createContext<number>(0);
export const ScrollElementContext = createContext<MutableRefObject<HTMLDivElement | null> | null>(null);

将上下文传输到layout.tsx会产生相同的错误. 此问题适用于文件中的所有上下文.

上下文键入有什么问题?我怎么才能解决这个问题呢?

推荐答案

try 像这样创建上下文

import { createContext } from "react";

interface ModalContextProps {
  show: (content: ReactNode) => void;
  hide: () => void;
}

const ModalContext = createContext<ModalContextProps | undefined>(undefined);

export function ModalProvider({ children }: { children: ReactNode }) {
  const [modalContent, setModalContent] = useState<ReactNode | null>(null);
  const [showModal, setShowModal] = useState(false);

  const show = (content: ReactNode) => {
    setModalContent(content);
    setShowModal(true);
  };

  const hide = () => {
    setShowModal(false);
    setTimeout(() => {
      setModalContent(null);
    }, 300); // Adjust this timeout as per your transition duration
  };

  return (
    <ModalContext.Provider value={{ show, hide }}>
      {children}
      {showModal && (
        <Modal showModal={showModal} setShowModal={setShowModal}>
          {modalContent}
        </Modal>
      )}
    </ModalContext.Provider>
  );
}

export function useModal() {
  return useContext(ModalContext);
}

Typescript相关问答推荐

TypScript如何在 struct 上定义基元类型?

有没有可能使用redux工具包的中间件同时监听状态的变化和操作

如何判断输入是否是TypeScript中的品牌类型?

当我点击外部按钮时,如何打开Html Select 选项菜单?

为什么从数组中删除一个值会删除打字错误?

打印脚本丢失函数的泛型上下文

如何键入函数以只接受映射到其他一些特定类型的参数类型?

如何将所有props传递给React中的组件?

如何将泛型对象作为返回类型添加到类型脚本中

Cypress页面对象模型模式.扩展Elements属性

限制返回联合的TS函数的返回类型

`fetcher.load`是否等同于Get Submit?

创建一个TypeScrip对象并基于来自输入对象的约束定义其类型

如何解决&Quot;类型不可分配给TypeScrip IF语句中的类型&Quot;?

递归生成常量树形 struct 的键控类型

基于区分的联合键的回调参数缩小

如何在TypeScript中将元组与泛型一起使用?

如何使用 AWS CDK 扩展默认 ALB 控制器策略?

从 npm 切换到 pnpm 后出现Typescript 错误

如何使用布尔值构建对象 TYPE,但至少有一个必须为 true