kit icon indicating copy to clipboard operation
kit copied to clipboard

`invalid` returns an incomplete `ActionResult`

Open cdcarson opened this issue 3 years ago • 2 comments

Describe the bug

I'm getting a typescript error when I do this...

import { invalid, type Actions, type ActionResult } from '@sveltejs/kit';

type Invalid = { message: string; lucky: number };
type Success = { message: string; lucky: number };

export const actions: Actions = {
  default: (): ActionResult<Success, Invalid> => {
    const lucky = Math.random();
    if (lucky > 0.499999) {
      return { status: 200, type: 'success', data: { message: 'Yay!', lucky } };
    }
    return invalid(400, { message: 'Boo', lucky }); // <-- error here
  }
};

Error:

Type 'ValidationError<{ message: string; lucky: number; }>' is not assignable to type 'ActionResult<Success, Invalid>'.
  Property 'type' is missing in type 'ValidationError<{ message: string; lucky: number; }>' but required in type '{ type: "invalid"; status: number; data?: Invalid | undefined; }'.ts(2322)
index.d.ts(381, 6): 'type' is declared here.

This is just a typescript thing. The action works as expected in real life (I didn't actually test it in the repro below) because handle_action_json_request adds the type if it encounters on instance of ValidationError.

Should ValidationError have public type = 'invalid'? The constructor is only used by invalid. Not sure where else invalid is used, besides in the context of actions.

Reproduction

https://github.com/cdcarson/sk-action-types-issue.git

Logs

See error above

System Info

System:
    OS: macOS 12.5.1
    CPU: (8) arm64 Apple M1
    Memory: 95.17 MB / 8.00 GB
    Shell: 5.8.1 - /bin/zsh
  Binaries:
    Node: 16.17.0 - ~/.nvm/versions/node/v16.17.0/bin/node
    npm: 8.15.0 - ~/.nvm/versions/node/v16.17.0/bin/npm
  Browsers:
    Chrome: 105.0.5195.102
    Safari: 15.6.1
  npmPackages:
    @sveltejs/adapter-auto: next => 1.0.0-next.75 
    @sveltejs/kit: next => 1.0.0-next.483 
    svelte: ^3.44.0 => 3.50.1 
    vite: ^3.1.0 => 3.1.1

Severity

annoyance

Additional Information

No response

cdcarson avatar Sep 15 '22 17:09 cdcarson

ActionResult isn't meant to be used as the return type of an Action - although I now realize that the name is probably misleading in that regard. ActionResult is the type of the JSON response (when you fetch the action, through use:enhance for example). There's no return type that exists for Action, so you are free to create one yourself similarly to what you did.

Giving this the documentation label to document this on ActionResult

dummdidumm avatar Sep 15 '22 19:09 dummdidumm

ActionResult is the type of the JSON response (when you fetch the action, through use:enhance for example).

@dummdidumm Ok, thanks. I got the wrong end of the stick somehow. I'll close the PR, but leave this open.

cdcarson avatar Sep 15 '22 19:09 cdcarson