打字稿反应上下文+类型'{}'没有调用签名

Typescript react context + Type '{}' has no call signatures

我创建了一个 Notification Toast 服务,除了 ToastContext 周围的一些打字稿错误外,它似乎可以正常工作。

在我导入连接到 contextProvider 的 useToast() 挂钩的任何页面上调用 toast。 toast(...) 函数出现打字稿错误。我收到的错误是

错误 This expression is not callable. Type '{}' has no call signatures.

吐司挂钩

<button
    onClick={() => {
        return toast({
            title: "I am toasty"
        });
    }}
>Toast Me</button>

上下文和使用上下文钩子

export const ToastContext = createContext({});

export function useToast() {
  return useContext(ToastContext);
}

这里是当前代码的codesandbox https://codesandbox.io/s/dazzling-spence-clehl

我尝试使用

键入我的 createContext
interface ContextType {
   toasts: []
   toast: () => void
}

export const ToastContext = createContext<ContextType | {}>({});

你的上下文值是一个函数,而你用一个空对象初始化上下文(为什么?),所以在静态类型评估中,调用 toast() 是尝试在对象上发出一个函数('{}' has no call signatures).

根据其用法修复您的初始化:

// toast is a function
<ToastContext.Provider value={toast}>{children}</ToastContext.Provider>

export const ToastContext = createContext((payload: any) => {});

或者,我猜你最初的想法是尝试做类似的事情:

// import ToastProps
interface ContextType {
  toasts: [] | ToastProps[];
  toast: (payload: any) => void;
}

export const ToastContext = createContext<ContextType>({
  toast: () => {},
  toasts: []
});

// Initilization
const { toast, toasts } = useToasts();

// Pass ContextType
<ToastContext.Provider value={{toast, toasts}}>{children}</ToastContext.Provider>

// Context usage
const { toast } = useToast();
toast(); // is a function, GOOD

其中 ContextType 匹配 useToast return 值和 createContext(尝试将 ContextTypeuseToast return 值重用) .