Home > Back-end >  Typescript doesn't complain when misusing a function passed as a prop in React
Typescript doesn't complain when misusing a function passed as a prop in React

Time:09-30

I have one React component defined as follows:

const BirthdaySearch: FC<{ onSearch: (year: string, month: string) => void }> =
  (props) => {
    const monthInputRef = useRef<HTMLInputElement>(null);
    const dayInputRef = useRef<HTMLInputElement>(null);

    const submitHandler = (e: FormEvent<HTMLFormElement>) => {
      e.preventDefault();

      const selectedDay = dayInputRef!.current!.value;
      const selectedMonth = monthInputRef!.current!.value;

      props.onSearch(selectedYear, selectedMonth);
    };

    return (
      <form onSubmit={submitHandler}>
        <div>
          <div>
            <label htmlFor="month">Month</label>
            <input name="month" id="month" ref={monthInputRef} />
          </div>
          <div>
            <label htmlFor="month">Day</label>
            <input name="day" id="day" ref={dayInputRef} />
          </div>
        </div>
        <Button>Find People By Birthday</Button>
      </form>
    );
  };

export default BirthdaySearch;

The onSearch function is typed in the props of the element, but when it's misused in the parent component by mentioning fewer arguments than are defined in the child component, TypeScript doesn't mind:

const Birthdays: NextPage = () => {
  const findBdHandler = () => {
    // do things...
  };

  return <BirthdaySearch onSearch={findBdHandler} />
    
};

export default Birthdays;

TypeScript only complains if the types are wrong or there are more arguments than defined in the child. Is there a way to make this more strict?

CodePudding user response:

The reason that typescript doesn't complain is that the code is perfectly valid: it is perfectly fine and common practice to ignore parameters for a function. For example, onClick handlers often get the event as a parameter, but if you don't care about the event you can just pass in a handler that doesn't take parameters.

CodePudding user response:

Typescript or for that matter any other type checker would not throw an error when you use lesser params than specified (They would show an error if you mention a param as variable and then leave it unused).

If you want to make it strict to check the values then you should type it at the parent level then use the function in the child. This should throw an error when the child does not pass the required params.

Definitions flow from parent to child and not the other way.

Hopefully I've explained it clearly

  • Related