[英]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?我试图在反应 typescript 应用程序中将道具标记为必需道具,我该怎么做? Using react with js, one chains
isRequired
keyword on the type.使用 React with js,在类型上使用一个链
isRequired
关键字。 How can i do this with ts?我怎么能用 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这是我试图重现的 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我认为您必须为
HelloWorld
function 明确指定 output 类型
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.
你不需要额外的类型检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.