Search code examples
typescripttypes

Can't set React useFormState type property to null despite having set null as an option


I'm working with Typescript. I have a type with a property 'message' that can be string or null

export type State = {
  message: string | null;
};

Altough, when trying to set that property to null I get the following type error. It only allows me to set it to string.

Types of property 'message' are incompatible.
Type 'null' is not assignable to type 'string'.

I'm using the type like this:

const initialState = { message: null };
const [state, dispatch] = useFormState(postFiles, initialState);

export async function postFiles(prevState: State, formData: FormData) {
  console.log(formData);
  return {
    message: "Uploaded",
  };
}

I've tried setting strictNullChecks to true, but I'm still getting the error. What could it be? is there something I'm missing?


Solution

  • The problem is because the type of useFormState is as follows:

        function useFormState<State, Payload>(
            action: (state: Awaited<State>, payload: Payload) => State | Promise<State>,
            initialState: Awaited<State>,
            permalink?: string,
        ): [state: Awaited<State>, dispatch: (payload: Payload) => void];
    

    Since action is defined as (state: Awaited<State>, payload: Payload) => State, that means that the return value of that action, in this case postFiles, will be automatically inferred as State.

    That return value is an object literal where message is a string. That means initialState: Awaited<State> evaluates to a type where message is a string (since it's inferred from that return value) so your null value for message in the object passed to the initial values is not valid against this automatically inferred type.

    To fix, explicitly pass the type arguments so TS knows ahead of time what this value can be.

    const [state, dispatch] = useFormState<State, FormData>(postFiles, initialState);