State Type
is not assignable to type 'null'
Your state is defined such that selectedBank can only be null and anything else will give an error. Since your defaultState has selectedBank: null, Typescript will infer the type for this property as null unless you tell it otherwise.
You can declare the type for the state either by assigning a type to the defaultValue variable
const defaultState: MyState = {
or the generic on the useState hook
const [state, setState] = useState<MyState>(defaultState);
You just need one of those, not both.
The type for MyState should be such that selectedBank can be null, but can also be the value that you want.
Event Type
I am assuming that the react-select tag means you are using the react-select package? Different packages and components define their own change event types. react-select calls onChange with two arguments which are the option and an ActionMeta object.
import React, { useState } from "react";
import Select from "react-select";
interface Bank {
label: string;
value: string;
}
type MyState = {
buttonDisabled: boolean;
selectedBank: Bank | null;
};
export const MyComponent = ({ options }: { options: Bank[] }) => {
const defaultState: MyState = {
buttonDisabled: true,
selectedBank: null
};
const [state, setState] = useState(defaultState);
function handlerSelectBank(selectedBank: Bank | null) {
setState({
...state,
buttonDisabled: false,
selectedBank
});
}
return (
<Select
value={state.selectedBank}
options={options}
onChange={handlerSelectBank}
/>
);
};
It might be easier to have separate useState hooks for separate pieces of data.
const handlerSelectBank = (event: type_of_your_value | null) => .., So, maybe(event: string |null)by guessing that you need a string forselectedBank. It should show you in your editor (e.g. VSCode) when you hover mouse over theonChangeprops of react-select.selectelement in React? The answer might be different.defaultState. If it hasselectedBank: nullthen you need to assign a type to it whereselectedBankis the union ofnulland something else. Otherwise it can only ever benull.