Skip to content

Instantly share code, notes, and snippets.

@miladvafaeifard
Last active August 24, 2019 19:50
Show Gist options
  • Save miladvafaeifard/054642c19a6c1351001bf12409f0ce0f to your computer and use it in GitHub Desktop.
Save miladvafaeifard/054642c19a6c1351001bf12409f0ce0f to your computer and use it in GitHub Desktop.
Typescript referring React proptypes
import * as React from "react";
import { render } from "react-dom";
import * as PropTypes from "prop-types";
const userPropTypes = {
name: PropTypes.string.isRequired,
className: PropTypes.string
};
const userDefaultProps = {
className: "test-class"
};
type InferPropTypes<
PropTypes,
DefaultProps = {},
Props = PropTypes.InferProps<PropTypes>
> = {
[Key in keyof Props]: Key extends keyof DefaultProps
? Props[Key] | DefaultProps[Key]
: Props[Key]
};
type UserProps = InferPropTypes<typeof userPropTypes, typeof userDefaultProps>;
class User extends React.Component<UserProps> {
static propTypes: {};
static defaultProps = userDefaultProps;
render() {
let { name, className } = this.props;
console.log("className: ", className);
// Note: strict mode is enabled in tsconfig.json
return (
<div className={className}>
<h1>Hello, {name}</h1>
</div>
);
}
}
User.propTypes = userPropTypes;
const rootElement = document.getElementById("root");
render(<User name="User" className="test-mil" />, rootElement);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment