kiliman / remix-typedjson

This package is a replacement for superjson to use in your Remix app. It handles a subset of types that `superjson` supports, but is faster and smaller.
MIT License
435 stars 19 forks source link

Upgrade to remix 2 broke type inference on ActionData #34

Closed cayblood closed 10 months ago

cayblood commented 10 months ago

I had an action like this:

export const action: ActionFunction = async ({ request, params }) => {
  // ... 
  if (condition) {
    // ...
    if (result.success) {
      return typedjson({ status: 'success' }, 200);
    }
    return typedjson({ errors: result.errors, status: 'error' }, 400);
  }
  throw redirect('/app/employer/contractors');
};

And in my component I have:

  const actionData = useTypedActionData<typeof action>();
  const { show } = useToastControls();
  useMemo(() => show('notification'), [show]);
  useEffect(() => {
    if (actionData?.status === 'success') {
      show('notification');
    }
  }, [show, actionData]);

This used to infer the type just fine. Now I get a typescript error:

TS2339: Property 'status' does not exist on type '{} | Response'.
Property 'status' does not exist on type '{}'.

Any ideas why?

kiliman commented 10 months ago

Try changing your action signature to type the arguments instead of the function. The ActionFunction type messes with inference because it forces TS to use Response as the return type.

import { type DataFunctionArgs } from '@remix-run/node'
export const action = async ({ request, params }: DataFunctionArgs) => {
  //...
}
cayblood commented 10 months ago

Thanks. That worked!