如何在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;

这是我要复制的jsx

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;
评论
  • 随怀芹
    随怀芹 回复

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

    function HelloWorld({ message }: Props): React.SFC<Props> {
      return <div>Hello {message}</div>;
    }
    
  • _堅=強
    _堅=強 回复

    应为:

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