If you want to use null type then the initial state shouldn't be undefined
const [person, setPerson] = useState<Person | null>(null)
In order to use both functional state update and normal state update, the type of setPerson can be
setPerson: Dispatch<SetStateAction<Person | null>>;
if you're passing this as a prop to a child component, the props interface should look like this
interface ChildProps {
setPerson: Dispatch<SetStateAction<Person | null>>;
}
const Child: FunctionComponent<ChildProps> = ({ setPerson }) => {
return (
<button
onClick={() => {
const updatedPerson = {
name: "vuvu",
age: 69,
job: "foo"
};
setPerson((prevPerson) => ({ ...prevPerson, ...updatedPerson }));
}}
>
Update Person
</button>
);
};
Here's a working codesandbox example
and as the age, name, job properties are not optional, make sure that you update the state with a person object that has all three fields. Alternatively, you can make some fields optional, like
interface Person {
name: string;
age: number;
job?: string; // this is optional
}
setPersonin the same component? If you're passing it as props make sure that the props interfaces have the correct type.useState<Person | null>()should beuseState<Person | undefined>()useState<Person | null>(null). Add the props interface of the child component to the question.