Home > other >  Property 'onClick' is missing in type '{ rating: any; }' but required in type &#
Property 'onClick' is missing in type '{ rating: any; }' but required in type &#

Time:07-28

I have a simple rating component in reactjs with typescript as follows

Rating.js

export type RatingType = {
  rating: number,
  onClick: (x: number) => void
  style?: React.CSSProperties,
  prod?: any
}

const Rating: React.FC <RatingType> = ({ rating, onClick, style }) => {
  return (
    <>
      //do something here
    </>
  );
};

export default Rating;

I would like to use this rating component in another component but without the onClick function like this below

import Rating from "./Rating";
function Demo() {
  return (
    //logic goes here
    <Rating rating={item.ratings}  />
  )
}

export default Demo

But I get the following error

Property 'onClick' is missing in type '{ rating: any; }' but required in type 'RatingType'.

How can I make the onClick function option when defining the type RatingType?

CodePudding user response:

If you don't want onClick to be required, just make it optional like this:

export type RatingType = {
  rating: number,
  onClick?: (x: number) => void // <- Add question mark there
  style?: React.CSSProperties,
  prod?: any
}

const Rating: React.FC <RatingType> = ({ rating, onClick, style }) => {
  return (
    <>
      //do something here
    </>
  );
};

export default Rating;

CodePudding user response:

To make onClick optional just change RatingType to:

export type RatingType = {
  rating: number,
  onClick?: (x: number) => void, // NOTE the ? to make property optional
  style?: React.CSSProperties,
  prod?: any
}

Note the ? after the onClick

  • Related