メインコンテンツにスキップ

生成された型

RequestHandler型とLoad型はどちらもParams引数を受け取り、paramsオブジェクトの型を指定できます。例えば、このエンドポイントはfoobarbazパラメータを期待します。

src/routes/[foo]/[bar]/[baz]/+page.server
/** @type {import('@sveltejs/kit').RequestHandler<{
	foo: string;
	bar: string;
	baz: string
  }>} */
export async function 
function GET({ params }: {
    params: any;
}): Promise<void>
@type{import('@sveltejs/kit').RequestHandler<{ foo: string; bar: string; baz: string }>}
GET
({ params: anyparams }) {
// ... }
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: stringfoo: string; bar: stringbar: string; baz: stringbaz: 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ファイルを生成します。

.svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.d
import type * as module "@sveltejs/kit"Kit from '@sveltejs/kit';

type 
type RouteParams = {
    foo: string;
    bar: string;
    baz: string;
}
RouteParams
= {
foo: stringfoo: string; bar: stringbar: string; baz: stringbaz: 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オプションのおかげで、エンドポイントとページに兄弟としてインポートできます。

src/routes/[foo]/[bar]/[baz]/+page.server
/** @type {import('./$types').PageServerLoad} */
export async function function GET(event: ServerLoadEvent<RouteParams, Record<string, any>, string | null>): MaybePromise<void | Record<string, any>>
@type{import('./$types').PageServerLoad}
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: PageServerLoadGET: 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
}) => {
// ... };
src/routes/[foo]/[bar]/[baz]/+page
/** @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>>
@type{import('./$types').PageLoad}
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: PageLoadload: 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-kitoutDirです)を拡張する必要があります。

{ "extends": "./.svelte-kit/tsconfig.json" }

デフォルトのtsconfig.json

生成された.svelte-kit/tsconfig.jsonファイルには、さまざまなオプションが含まれています。一部はプロジェクト設定に基づいてプログラムで生成されるため、正当な理由がない限り、一般的にオーバーライドしないでください。

.svelte-kit/tsconfig
{
	"compilerOptions": {
		"baseUrl": "..",
		"paths": {
			"$lib": "src/lib",
			"$lib/*": "src/lib/*"
		},
		"rootDirs": ["..", "./types"]
	},
	"include": ["../src/**/*.js", "../src/**/*.ts", "../src/**/*.svelte"],
	"exclude": ["../node_modules/**", "./**"]
}

その他はSvelteKitが正常に動作するために必要であり、何をしているのか理解していない限り、変更しないでください。

.svelte-kit/tsconfig
{
	"compilerOptions": {
		// this ensures that types are explicitly
		// imported with `import type`, which is
		// necessary as svelte-preprocess cannot
		// otherwise compile components correctly
		"importsNotUsedAsValues": "error",

		// Vite compiles one TypeScript module
		// at a time, rather than compiling
		// the entire module graph
		"isolatedModules": true,

		// TypeScript cannot 'see' when you
		// use an imported value in your
		// markup, so we need this
		"preserveValueImports": true,

		// This ensures both `vite build`
		// and `svelte-package` work correctly
		"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

サーバーのフックhandlehandleError)、サーバー専用のload関数、および+server.jsファイルでアクセスできるevent.localsを定義するインターフェースです。

interface Locals {}

PageData

$page.dataストアの共通の形状、つまりすべてのページ間で共有されるデータを定義します。 ./$typesLoad関数とServerLoad関数は、それに応じて絞り込まれます。特定のページにのみ存在するデータには、オプションのプロパティを使用します。インデックスシグネチャ([key: string]: any)を追加しないでください。

interface PageData {}

PageState

$app/navigationpushState関数とreplaceState関数を使用して操作できる$page.stateオブジェクトの形状です。

interface PageState {}

Platform

アダプターがevent.platformを介してプラットフォーム固有のコンテキストを提供する場合、ここで指定できます。

interface Platform {}

GitHubでこのページを編集する