I've been searching through many forums and articles and did not find any successful way to define an interface for a function component in React that has required properties which are defined in defaultProps without throwing a "property is missing" Typescript error.
I've tried to set a default value directly in props but it doesn't work either. Is there any way or it's unresolved issue in React and Typescript?
To see this problem in action, I've provided CodeSandbox project.
type ButtonProps = {
color: "white" | "green";
};
const Button: FunctionComponent<ButtonProps> = ({
// First way to define default value
color = "green",
children
}) => <ButtonContainer>{children}</ButtonContainer>;
// Second way to define default value
Button.defaultProps = {
color: "white"
} as Partial<ButtonProps>;
const ButtonContainer = styled.button<ButtonProps>`
background-color: ${(props: ButtonProps) => props.color};
`;
const App: FunctionComponent = () => (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
{/* Here is an error */}
<Button>hello world</Button>
</div>
);