如何强类型 SvelteKit 请求处理程序?

TJB*_*man 4 typescript sveltekit

我有一个独立的 sveltekit 端点,但我没有获得该端点的打字稿类型。

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

  return { status: 200, body: "ok" };
}
Run Code Online (Sandbox Code Playgroud)

参数request有一个any类型,而函数本身有一个返回类型,Promise<any>这不是我想要的。

我从 sveltekit 定义的类型中找到了,但我不确定如何实现它们。
import type {RequestHandler} from '@sveltejs/kit'

我如何告诉打字稿该post()函数是类型RequestHandler

另外,tsconfig.json我的项目根目录中有一个自定义文件,但即使删除它,我仍然无法获得端点函数的正确类型。

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

Run Code Online (Sandbox Code Playgroud)

zee*_*rey 6

我一直在寻找同样的东西。我现在将采用以下解决方案:

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

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

    return { status: 200, body: 'ok' };
};
Run Code Online (Sandbox Code Playgroud)


Luc*_*ley 5

SvelteKit 文档中生成类型的示例适用于 JSDoc。使用打字稿,我们可以导入并应用类型:-)希望有帮助!

// 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"
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您确定要使用某个函数,我不相信它会为您生成这些类型,因此您可以像这样输入它们。

// 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" }
}
Run Code Online (Sandbox Code Playgroud)