I have an issue with typescript and react. Bellow is a small exmaple that illustrates the problem.
const Example = (props: { x?: number, fn: (x: number) => void}) => {
if (props.x !== undefined) {
return <button onClick={() => props.fn(props.x)}>Click me</button>
}
return null;
}
Code checks explicitly that x is defined but typescript won't compile it because fn requires x to be a number. It can be solved using casting
const y = props.x as number;
return <button onClick={() => props.fn(y)}>Click me</button>
It works but looks weird. Any ideas how to handle such cases. It's just an example in my code we have an object instead of a number and it also either defined and then we render some html for it or not defined (=== undefined) and than we just return null.