简体   繁体   中英

How do I strongly type a SvelteKit Request Handler?

I have a standalone sveltekit endpoint, and I'm not getting typescript typings for the endpoint.

// src/routes/login.ts
export async function post(request) {
  request.body; // shows as 'any' type

  return { status: 200, body: "ok" };
}

The request argument has an any type, and the function itself has a return type of Promise<any> which is not what I want.

I've found from types defined by sveltekit, but I'm not sure how to implement them.
import type {RequestHandler} from '@sveltejs/kit'

How can I tell typescript that the post() function is of type RequestHandler ?

Also, I have a custom tsconfig.json file in the root of my project, but even when I delete this, I still don't get proper typings of my endpoint functions.

// tsconfig.json
{
    "extends": "./.svelte-kit/tsconfig.json",
    "compilerOptions": {
        "baseUrl": ".",
        "paths": {
            "$src/": ["src/"],
            "$src/*": ["src/*"]
        },
        "typeRoots": ["node_modules/@types", "src/types"]
    }
}

I was searching for the same thing. I'll go with the following solution for now:

import type { RequestHandler } from '@sveltejs/kit';

export const post: RequestHandler = async ({ request }) => {
    request.body; // shows as 'ReadableStream<Uint8Array>' type

    return { status: 200, body: 'ok' };
};

The example in the SvelteKit docs for generated-types is for JSDoc. Using typescript we can just import and apply the type :-) Hope that helps!

// src/routes/login.ts
// Note we're importing the .d declaration file here
import type { RequestHandler } from './login.d' 

type Output = string // This will type your body
export const post: RequestHandler<Output> = async({ params }) => {
  return {
    status: 200,
    body: "ok"
  }
}

If you're for sure wanting to use a function I don't believe it will generate those types for you so you would type them like this.

// src/routes/login.ts
import type { RequestHandlerOutput } from '@sveltejs/kit'
import type { MaybePromise, RequestEvent } from '@sveltejs/kit/types/private';

// Type your respose body here
type GetOutput = {}
// Type your params here
interface GetParams extends Record<string, string> {}
function get(event: RequestEvent<GetParams>): MaybePromise<RequestHandlerOutput<GetOutput>> {
    
    return { status: 200 }
}

// Example using your post request

type PostOutput = string
// Type your params here
interface PostParams extends Record<string, string> {}
function post(event: RequestEvent<PostParams>): MaybePromise<RequestHandlerOutput<PostOutput>> {
    event.request.body; // shows as Body.body: ReadableStream<Uint8Array> | null

    return { status: 200, body: "ok" }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM