I'm having a little trouble using Typescript with React and useState.
Say I have something like,
type TPerson = {
name: string;
car: string;
};
export default function App() {
const [person, setPerson] = React.useState<TPerson>(null);
const handleClear = React.useCallback(() => {
setPerson(null);
}, []);
const { name, car } = person;
return (
<div className="App">
<h1>
{person.name} drives a {person.car}
</h1>
<button onClick={handleClear}>clear</button>
</div>
);
}
This would complain here,
const handleClear = React.useCallback(() => {
setPerson(null);
^^^^
Argument of type 'null' is not assignable to parameter of type
}, []);
Well, ok, let's fix that by changing up TPerson,
type TPerson = {
name: string;
car: string;
} | null;
That fixes that error, but now I get a new one,
<h1>
{person.name} drives a {person.car}
^^^^ ^^^
Object is possibly 'null'.
</h1>
Well that's easy, I'll just do,
<h1>
{person?.name ?? 'unknown name'} drives a {person?.car ?? 'unknown car'}
</h1>
But then I get this error,
const { name, car } = person;
^^^^ ^^^
Properties 'name' and 'car' do not exist on type 'TPerson'
Well, yeah, I guess, because TPerson can be null.
I can't even do,
const { name = '', car = '' } = person;
or,
type TPerson = {
name: string;
car: string;
};
. . .
const [person, setPerson] = React.useState<TPerson>({} as TPerson);
So what are my options here? If I have a modal that determines it's open state on whether or not person is null, how can I properly go about this?