Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to conditionally call different optional function props in a React TypeScript component without getting compiler error?

I have a React TypeScript component which accepts multiple props of which some are optional and these include functions as well. Below is a rough example of what my actual code looks like

interface AnimalProps {
  animalName: string;
  bark?: () => void;
  swim?: () => void;
}

const Animal = ({ animalName, bark, swim }: AnimalProps) => {
  /* some rendering here */
}

I also call the bark or swim function depending upon the animalName.
The issue is since both of these are optional props, typescript keeps throwing the error
Cannot invoke an object which is possibly undefined. How can I assert to the compiler that at least one of these function will definitely be passed depending upon the animalName ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can simply check if the function exists before calling it.

if (animalName === 'dog' && typeof bark === 'function') {
  bark();
}

If you feel like that is too verbose, you can also take advantage of optional-chaining to do the same thing.

if (animalName === 'dog') {
  bark?.(); // Will only invoke bark() if it's defined
}

Optional-chaining is supported in TypeScript since version 3.7.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading