Passing type to a hook just like useState

46 Views Asked by At

I have a custom hook built with Zustand that can store multiple types of data, but I want to be able to pass the type I will be using just like with the useState hook

import { Profile } from "@/types";
import { create } from "zustand";

type ActionData = Product | Category | Profile | null;

type ActionDataStore = {
    actionData: ActionData;
    setActionData: (actionData: ActionData) => void;
};

export const useActionData = create<ActionDataStore>((set) => ({
    actionData: null,
    setActionData: (actionData) =>
        set((state) => {
            return { actionData };
        }),
}));

This is how it should look like when I use it inside a component:

const {actionData, setActionData} = useActionData<Profile>()

Typescript should give me an error whenever i try to set the action data to anything other than a profile now. And actionData should be of type Profile aswell

1

There are 1 best solutions below

3
Malcolm Mutare On

To make the useActionData hook generic so that you can specify the type when using it in a component. You can achieve this by making the ActionDataStore and the useActionData hook generic. Try the code below:enter code here

import { create } from "zustand";
import { Profile, Product, Category } from "@/types";

type ActionData = Product | Category | Profile | null;

type ActionDataStore<T extends ActionData> = {
  actionData: T;
  setActionData: (actionData: T) => void;
};

export const useActionData = <T extends ActionData>(
  defaultData: T | null = null
) =>
  create<ActionDataStore<T>>((set) => ({
    actionData: defaultData,
    setActionData: (actionData) =>
      set((state) => {
        return { actionData };
      }),
  }));

// Below is the hook with Profile type
const { actionData, setActionData } = useActionData<Profile>();

Hope that helps