Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you mark a prop as required in react typescript?

I am trying to mark a prop as a required prop in a react typescript application, how can I do that? Using react with js, one chains isRequired keyword on the type. How can i do this with ts?

// Here is my typescript code:

interface Props {
  /** Message to display */
  message: string;
}

const defaultProps: Props = {
  message: 'World',
};
/** My first reusable component */
function HelloWorld({ message }: Props) {
  return <div>Hello {message}</div>;
}

HelloWorld.defaultProps = defaultProps;

Here is the jsx I am trying to reproduce

import PropTypes from 'prop-types';

function HelloWorld({message}) {
  return <div>Hello {message}</div>
}

HelloWorld.propTypes = {
  message: PropTypes.string.required
};

HelloWorld.defaultProps = {
  message: 'World'
};

export default HelloWorld;
like image 308
Gideon Bamuleseyo Avatar asked Oct 18 '25 20:10

Gideon Bamuleseyo


1 Answers

I think you have to explicitly specify output type for HelloWorld function

function HelloWorld({ message }: Props): React.SFC<Props> {
  return <div>Hello {message}</div>;
}

or

const HelloWorld: React.SFC<Props> = ({ message }) => {
  return <div>Hello {message}</div>;
}
like image 50
Józef Podlecki Avatar answered Oct 21 '25 09:10

Józef Podlecki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!