类型
生成的类型
RequestHandler
和 Load
类型都接受一个 Params
参数,允许您为 params
对象定义类型。例如,这个端点需要 foo
、bar
和 baz
参数:
/** @type {import('@sveltejs/kit').RequestHandler<{
foo: string;
bar: string;
baz: string
}>} */
export async function function GET({ params }: {
params: any;
}): Promise<void>
GET({ params: any
params }) {
// ...
}
import type { type RequestHandler<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, RouteId extends string | null = string | null> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>
A (event: RequestEvent) => Response
function exported from a +server.js
file that corresponds to an HTTP verb (GET
, PUT
, PATCH
, etc) and handles requests with that method.
It receives Params
as the first generic argument, which you can skip by using generated types instead.
RequestHandler } from '@sveltejs/kit';
export const const GET: RequestHandler<{
foo: string;
bar: string;
baz: string;
}>
GET: type RequestHandler<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, RouteId extends string | null = string | null> = (event: RequestEvent<Params, RouteId>) => MaybePromise<Response>
A (event: RequestEvent) => Response
function exported from a +server.js
file that corresponds to an HTTP verb (GET
, PUT
, PATCH
, etc) and handles requests with that method.
It receives Params
as the first generic argument, which you can skip by using generated types instead.
RequestHandler<{
foo: string
foo: string;
bar: string
bar: string;
baz: string
baz: string
}> = async ({ params: {
foo: string;
bar: string;
baz: string;
}
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) => {
// ...
};
显然,这样编写很麻烦,而且不够灵活(如果您将 [foo]
目录重命名为 [qux]
,类型将不再反映实际情况)。
为了解决这个问题,SvelteKit 为您的每个端点和页面生成 .d.ts
文件:
import type * as module "@sveltejs/kit"
Kit from '@sveltejs/kit';
type type RouteParams = {
foo: string;
bar: string;
baz: string;
}
RouteParams = {
foo: string
foo: string;
bar: string
bar: string;
baz: string
baz: string;
};
export type type PageServerLoad = (event: Kit.ServerLoadEvent<RouteParams, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad = module "@sveltejs/kit"
Kit.type ServerLoad<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, ParentData extends Record<string, any> = Record<string, any>, OutputData extends Record<string, any> | void = void | Record<...>, RouteId extends string | null = string | null> = (event: Kit.ServerLoadEvent<Params, ParentData, RouteId>) => MaybePromise<OutputData>
The generic form of PageServerLoad
and LayoutServerLoad
. You should import those from ./$types
(see generated types)
rather than using ServerLoad
directly.
ServerLoad<type RouteParams = {
foo: string;
bar: string;
baz: string;
}
RouteParams>;
export type type PageLoad = (event: Kit.LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad = module "@sveltejs/kit"
Kit.type Load<Params extends Partial<Record<string, string>> = Partial<Record<string, string>>, InputData extends Record<string, unknown> | null = Record<string, any> | null, ParentData extends Record<string, unknown> = Record<...>, OutputData extends Record<string, unknown> | void = void | Record<...>, RouteId extends string | null = string | null> = (event: Kit.LoadEvent<Params, InputData, ParentData, RouteId>) => MaybePromise<OutputData>
The generic form of PageLoad
and LayoutLoad
. You should import those from ./$types
(see generated types)
rather than using Load
directly.
Load<type RouteParams = {
foo: string;
bar: string;
baz: string;
}
RouteParams>;
这些文件可以作为同级文件导入到您的端点和页面中,这要归功于 TypeScript 配置中的 rootDirs
选项:
/** @type {import('./$types').PageServerLoad} */
export async function function GET(event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
GET({ params: RouteParams
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) {
// ...
}
import type { type PageServerLoad = (event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad } from './$types';
export const const GET: PageServerLoad
GET: type PageServerLoad = (event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageServerLoad = async ({ params: RouteParams
The parameters of the current route - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params }) => {
// ...
};
/** @type {import('./$types').PageLoad} */
export async function function load(event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
load({ params: RouteParams
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params, fetch: {
(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch
is equivalent to the native fetch
web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookie
and authorization
headers for the page request.
- It can make relative requests on the server (ordinarily,
fetch
requires a URL with an origin when used in a server context).
- Internal requests (e.g. for
+server.js
routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
text
and json
methods of the Response
object. Note that headers will not be serialized, unless explicitly included via filterSerializedResponseHeaders
- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here
fetch }) {
// ...
}
import type { type PageLoad = (event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad } from './$types';
export const const load: PageLoad
load: type PageLoad = (event: LoadEvent<RouteParams, Record<string, any> | null, Record<string, any>, string | null>) => MaybePromise<void | Record<string, any>>
PageLoad = async ({ params: RouteParams
The parameters of the current page - e.g. for a route like /blog/[slug]
, a { slug: string }
object
params, fetch: {
(input: RequestInfo | URL, init?: RequestInit): Promise<Response>;
(input: string | URL | globalThis.Request, init?: RequestInit): Promise<Response>;
}
fetch
is equivalent to the native fetch
web API, with a few additional features:
- It can be used to make credentialed requests on the server, as it inherits the
cookie
and authorization
headers for the page request.
- It can make relative requests on the server (ordinarily,
fetch
requires a URL with an origin when used in a server context).
- Internal requests (e.g. for
+server.js
routes) go directly to the handler function when running on the server, without the overhead of an HTTP call.
- During server-side rendering, the response will be captured and inlined into the rendered HTML by hooking into the
text
and json
methods of the Response
object. Note that headers will not be serialized, unless explicitly included via filterSerializedResponseHeaders
- During hydration, the response will be read from the HTML, guaranteeing consistency and preventing an additional network request.
You can learn more about making credentialed requests with cookies here
fetch }) => {
// ...
};
要使此功能生效,您的
tsconfig.json
或jsconfig.json
应该继承自生成的.svelte-kit/tsconfig.json
(其中.svelte-kit
是您的outDir
):
{ "extends": "./.svelte-kit/tsconfig.json" }
默认 tsconfig.json
生成的 .svelte-kit/tsconfig.json
文件包含多种选项。有些是根据您的项目配置以编程方式生成的,一般情况下不应该在没有充分理由的情况下覆盖:
{
"compilerOptions": {
"baseUrl": "..",
"paths": {
"$lib": "src/lib",
"$lib/*": "src/lib/*"
},
"rootDirs": ["..", "./types"]
},
"include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"],
"exclude": ["../node_modules/**", "./**"]
}
其他一些选项是 SvelteKit 正常工作所必需的,除非您知道自己在做什么,否则也不应该修改:
{
"compilerOptions": {
// 这确保类型使用 `import type` 显式导入,
// 这是必需的,因为 svelte-preprocess
// 否则无法正确编译组件
"importsNotUsedAsValues": "error",
// Vite 一次编译一个 TypeScript 模块,
// 而不是编译整个模块图
"isolatedModules": true,
// TypeScript 无法'看到'您在标记中
// 何时使用导入的值,所以我们需要这个
"preserveValueImports": true,
// 这确保 `vite build` 和
// `svelte-package` 都能正常工作
"lib": ["esnext", "DOM", "DOM.Iterable"],
"moduleResolution": "node",
"module": "esnext",
"target": "esnext"
}
}
$lib
这是一个指向 src/lib
的简单别名,或者指向在 config.kit.files.lib
中指定的任何目录。它允许您访问常用组件和实用工具模块,而无需使用 ../../../../
这样的路径。
$lib/server
$lib
的子目录。SvelteKit 会阻止您在客户端代码中导入 $lib/server
中的任何模块。参见仅服务端模块。
app.d.ts
app.d.ts
文件包含您的应用程序的环境类型,即无需显式导入就可以使用的类型。
这个文件中总是包含 App
命名空间。此命名空间包含几个影响您与某些 SvelteKit 功能交互的类型。
Error
定义预期和非预期错误的通用形状。预期错误使用 error
函数抛出。非预期错误由 handleError
钩子处理,这些钩子应该返回这种形状。
interface Error {…}
message: string;
Locals
定义 event.locals
的接口,可以在服务端hooks(handle
和 handleError
)、仅服务端的 load
函数和 +server.js
文件中访问。
interface Locals {}
PageData
定义 page.data state 和 $page.data store 的通用形状 - 即所有页面之间共享的数据。
./$types
中的 Load
和 ServerLoad
函数将相应地被收窄。
对于仅存在于特定页面上的数据,请使用可选属性。不要添加索引签名([key: string]: any
)。
interface PageData {}
PageState
定义 page.state
对象的形状,可以使用 $app/navigation
中的 pushState
和 replaceState
函数来操作。
interface PageState {}
Platform
如果您的适配器通过 event.platform
提供平台特定上下文,您可以在这里指定它。
interface Platform {}