Let's say I have the following state declared on my React component:
const [selectedUsers, setSelectedUsers] = useState<IUser['id'][]>();
Said state is used as the value for a third party HTML <select /> (Ant Design).
After I'm done using the <select /> I would like to clear it, which I easily can do by setting the value as null or undefined.
E.g.:
setSelectedUsers(null);
<select value={selectedUsers} /> // Is now null, no option is selected
However, I cannot pass null as the <select /> value due to the expected TS props on the select component as it expects to receive <IUser['id'][] | undefined>.
I.e.:
Type 'null' is not assignable to type 'string[] | undefined'.
Given the context above, is there any problem with passing undefined to the React state?
I.e.:
setSelectedUsers(undefined);
This is a question about best practices as the code above works perfectly if I use undefined instead of null.
Just pass it [] as string[]
setSelectedUsers([] as string[]);
That should do it.
Edited to include the stuff in the comments:
The way the original question was worded you're type is a one-element array, this should be defined as:
const [selectedUsers, setSelectedUsers] = useState<string[]>();
Then, the solution above will work.
Passing undefined as a value onto setState is perfectly fine. The value of the state, in your case selectedUsers, can be of any JavaScript type.
undefined is a "Primitive Value" in JavaScript and therefore a regular type. Find more about JavaScript types here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#javascript_types
The type and constructor should be
const [selectedUsers, setSelectedUsers] = useState<[IUser['id']] | null>(null);
if you want null to be the null value. (undefined implicitly works since you don't pass in an initial state, since that's implicitly undefined.)
However, if you want to be able to select multiple values, you are probably looking for
const [selectedUsers, setSelectedUsers] = useState<Array<IUser['id']> | null>(null);