Search code examples
reactjstypescript

How to type React prop that lifts state up


Simple React component:

interface Props {
  title: string;
  text: string;
  callback?: Promise<boolean>;
}

const ExampleComponent: React.FC<Props> = ({ title, text, callback }) => {
  SweetAlert.fire({
    title,
    text
  }).then(r => if (r.value) callback(r.value));
}

Getting a following error:

TS2349: This expression is not callable.   Type 'Promise<boolean>' has no call signatures.
TS2722: Cannot invoke an object which is possibly 'undefined'.

What type should have my callback?


Solution

  • Just define it as a function that takes one argument

    callback: (val: boolen) => void;
    

    And most likely you need to make it a required props if you're gonna call it. And if you want it be not required - just check if callback exists, like:

    if (callback) callback(value)