Home > Enterprise >  "Property does not exist on type" while using custom hook
"Property does not exist on type" while using custom hook

Time:12-12

I've declared a custom hook

type ControlContextProps =
  | {
      name: string | undefined;
      id: string | undefined;
      selectedOptions: String[] | undefined;
      onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
    }
  | {};

const FormControlContext = React.createContext<ControlContextProps>({});

const useFormControl = () => {
  const context = React.useContext(FormControlContext);
  return context;
};

When using it, accessing the fields described in ControlContextProps results in the typescript error "Property 'xxx' does not exist on type 'ControlContextProps'.ts(2339)". This occurs for any field.

  const { id, name, selectedOptions, onChange } = useFormControl();

What am I doing wrong?

Test it out here.

CodePudding user response:

Because {} has no properties

You wanted to do something like:

import { createContext, useContext } from "react";

type ControlContextProps = {
  name: string;
  id: string;
  selectedOptions: String[];
  onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
};

const FormControlContext = createContext<ControlContextProps | undefined>(
  undefined
);

const useFormControl = () => {
  const context = useContext(FormControlContext);
  if (!context) throw new Error("Context have to be used within the provider");
  return context;
};

export default function App() {
  const { id, name, selectedOptions, onChange } = useFormControl();
  return <></>;
}

CodePudding user response:

Make the type values optional rather than having {}

type ControlContextProps =
   {
      name?: string | undefined;
      id?: string | undefined;
      selectedOptions?: String[] | undefined;
      onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
    }

Demo

  • Related