solid-jssolid-start

SolidJS state type unknown useContext TypeScript


In my SolidJS and SolidStart project, I declared my CartContext in my CartContext.tsx


export const CartContext = createContext<>();

const stateDefault = { ... };
export type StatesT = typeof stateDefault;

export const CartContextProvider: Component<CartContextProviderProps> = (
    props: CartContextProviderProps,
) => {
    const [state, setState] = createStore<StateT>(stateDefault);

    return (
        <CartContext.Provider value={{ state, setState }}>
            {props.children}
        </CartContext.Provider>
    );
};

export const useCartContext = () => useContext(CartContext);

But when I use this context in my components:

const { state, setState } = useCartContext();

TypeScript gave me warning: Property 'state' does not exist on type 'unknown'.ts(2339)


Solution

  • Okay I figured it out. I needed to add a type at createContext()

    according to the CartContext.Provider value={{ state, setState }}:

    export type cartContextType = {
        state: StatesT;
        setState: (state: StatesT) => void;
    };
    export const CartContext = createContext<cartContextType>();
    

    Then TypeScript gave me another warning: Property 'state' does not exist on type 'cartContextType | undefined'.ts(2339)

    according to this docs: https://docs.solidjs.com/reference/component-apis/create-context, you need to handle context === undefined case:

    export const useCartContext = () => {
        const context = useContext(CartContext);
        if (!context) throw new Error("CartContext is not valid");
        return context;
    };