Skip to content

Cannot use interfaces to type endpoint outputs #1997

@JeanJPNM

Description

@JeanJPNM

Describe the bug

When setting up and endpoint with typescript, it is not possible to have interfaces as endpoint outputs

Reproduction

// can be any endpoint
import type { RequestHandler } from '@sveltejs/kit';
type GetOutput = {
  message: string;
};
interface PostOutput {
  message: string;
}
type PutOutput = PostOutput;

// works
export const get: RequestHandler<unknown, unknown, GetOutput> = async () => {
  return {
    status: 200,
    body: {
      message: 'hello world',
    },
  };
};

// complains
export const post: RequestHandler<unknown, unknown, PostOutput> = async () => {
  return {
    status: 200,
    body: {
      message: 'hello world',
    },
  };
};

// complains
export const put: RequestHandler<unknown, unknown, PutOutput> = async () => {
  return {
    status: 200,
    body: {
      message: 'hello world',
    },
  };
};

Logs

src/routes/demo.ts:20:53 - error TS2344: Type 'PostOutput' does not satisfy the constraint 'DefaultBody'.
  Type 'PostOutput' is not assignable to type '{ [x: string]: JSONValue; }'.
    Index signature is missing in type 'PostOutput'.

20 export const post: RequestHandler<unknown, unknown, PostOutput> = async () => {
                                                       ~~~~~~~~~~

src/routes/demo.ts:30:52 - error TS2344: Type 'PostOutput' does not satisfy the constraint 'DefaultBody'.

30 export const put: RequestHandler<unknown, unknown, PutOutput> = async () => {
                                                      ~~~~~~~~~


Found 2 errors.

System Info

System:
    OS: Windows 10 10.0.19043
    CPU: (4) x64 Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz   
    Memory: 375.01 MB / 3.89 GB
  Binaries:
    Node: 14.14.0 - C:\Program Files\nodejs\node.EXE        
    npm: 6.14.8 - C:\Program Files\nodejs\npm.CMD
  Browsers:
    Chrome: 92.0.4515.107
    Edge: Spartan (44.19041.1023.0), Chromium (91.0.864.71) 
    Internet Explorer: 11.0.19041.1
  npmPackages:
    @sveltejs/adapter-node: ^1.0.0-next.35 => 1.0.0-next.35
    @sveltejs/kit: ^1.0.0-next.136 => 1.0.0-next.136
    svelte: ^3.40.1 => 3.40.1
    vite: ^2.4.3 => 2.4.3

Severity

blocking an upgrade

Additional Information

The issue is inside the JSONValue type, using it seems to require all the types assigned to it to have string indexes, can be worked around by using the unsafe any type, which defeats the whole purpose of having a typed endpoint

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationp2-nice-to-haveSvelteKit cannot be used by a small number of people, quality of life improvements, etc.types / typescript

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions