I am fairly new to Typescript and have one question about it.
In React, I encountered a situation whereby the state of a component can be undefined or a number. And I have a function that must use that particular state object as argument to dispatch action (let say calling API), and the argument cannot be undefined in order to call the API. Code is below.
interface IState {
someId?: number;
}
const mapDispatchToProps = (dispatch: Dispatch): IPropsFromDispatch => ({
getSettings: someId => dispatch(getRequest(someId)),
});
class someComponent extends React.PureComponent<IProps, IState> {
public constructor(props: IProps) {
super(props);
this.state = {
someId: undefined
};
}
public componentDidUpdate(prevProps: IProps, prevState: IState) {
if (this.state.someId !== prevState.someId) {
this.props.getSettings(this.state.someId);
}
}
public render() {
return (
<Dropdown
handleOnSelect={(e) => {this.setState({someId: e.target.value })} }
/>
)
}
}
Basically the someId state initially is undefined, but after selecting through dropdown, it will set the state for someId and trigger the dispatch getSettings action. If I specify type format of the dispatch,
interface IPropsFromDispatch {
getSettings(someId: number): void;
}
it will throw me an error saying
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.
The error will be gone if I do this of course
interface IPropsFromDispatch {
getSettings(someId?: number): void;
}
But I dont think this is recommended in using Typescript, since the dispatch action expects to have the someId as a number, not undefined, to be able to work. Or am I wrong? How should I do this?