I\'m trying to create a stateless React component with optional props and defaultProps in Typescript (for a React Native project). This is trivial with vanilla JS, but I\'m stum
To me, this doesn't look like a typescript issue.
DISCLAIMER: I have only tried this with typescript.
However, the problem is that props always exists (even as an empty object when nothing is passed in). There are 2 workaround for this, though.
The first, unfortunately, kills the super clean curly-brace-less syntax you have, but let's you keep defaultProps
around.
interface TestProps {
title?: string;
name?: string;
}
const defaultProps: TestProps = {
title: 'Mr',
name: 'McGee'
}
const Test = (passedIn: TestProps) => {
const props = Object.assign({}, defaultProps, passedIn);
return (
{props.title} {props.name}
);
}
another alternative that might get a little hairy if you have a TON of props, but that lets you keep your original syntax is something like this:
const Test = (props: TestProps) => (
{props.title || 'Mr'} {props.name || 'McGee'}
);
Hope this helps!