Skip to content

Instantly share code, notes, and snippets.

@caleb15
Last active July 18, 2019 22:12
Show Gist options
  • Save caleb15/21487d12261fe6423ba0c1643fe68c80 to your computer and use it in GitHub Desktop.
Save caleb15/21487d12261fe6423ba0c1643fe68c80 to your computer and use it in GitHub Desktop.
// simple types: see https://learnxinyminutes.com/docs/typescript/
/////////////////////////////////////////////////////////////////////////////
// generic function
// old:
const foo: a => a;
// new:
const foo: <T extends any>(a: T) => a;
/////////////////////////////////////////////////////////////////////////////
// React onWhatever functions (ex: onConfirm, onClick, etc...):
// old:
onConfirm = PropTypes.Function;
//new: (inspect type of onWhatever and use the same type)
const onConfirm: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void;
// note that you can import types from libraries and index types
// (assuming you installed the type library)
// ex:
import { ReactPaginateProps } from 'react-paginate';
onPageChange: ReactPaginateProps['onPageChange'];
// the benefit of doing this is that the type may change when the library is updated and you won't have to update your type
/////////////////////////////////////////////////////////////////////////////
// RouteComponentProps
// old:
type Props = {
history: {
push: Function;
};
location: {
search: string;
};
foo: string;
};
// new:
import { RouteComponentProps } from 'react-router-dom';
interface Props extends RouteComponentProps {
foo: string;
}
// old:
type Props = {
match: {
params: {
text: string;
};
};
history: {
push: Function;
};
location: {
search: string;
};
foo: string;
};
// new:
import { RouteComponentProps } from 'react-router-dom';
interface Props
extends RouteComponentProps<{
text: string;
}> {
foo: string;
}
/////////////////////////////////////////////////////////////////////////////
// Stateless components:
// old: function foo(props) {}; foo.defaultProps = defaultProps;
// new:
const foo: React.FunctionComponent<Props> = props => {
// code
}
foo.defaultProps = {
foo: true,
};
// children are not needed anymore
// get rid of children?: React.ReactNode; in your props
/////////////////////////////////////////////////////////////////////////////
// Wrapped Components:
// old:
export default function withPaginate(WrappedComponent) {
class WithPaginate {
constructor(props) {}
}
}
// new:
const withFoo = <P extends object>(
WrappedComponent: React.ComponentType<P>,
) => {
class WithPaginate extends React.Component<P> {
constructor(props: P) {}
}
}
export default withFoo;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment