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;
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>;
}
I don't really get what you mean? If you define an interface without optional fields, all of them are required by default? Yout don't need extra type checking.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.