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

2024-04-30

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

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

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

The 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"]
    }
}


SvelteKit 文档中的示例生成类型 https://kit.svelte.dev/docs/types#generated-types用于 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"
  }
}

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

// 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" }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何强类型 SvelteKit 请求处理程序? 的相关文章

随机推荐