Skip to main content

Types

Edit this page on GitHub

Public types

The following types can be imported from @sveltejs/kit:

Action

Shape of a form action method that is part of export const actions = {..} in +page.server.js. See form actions for more information.

ts
interface Action<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> {}
ts
(event: RequestEvent<Params, RouteId>): MaybePromise<OutputData>;

ActionResult

fetch を通じて form action を呼び出したとき、そのレスポンスはこれらの形となります。

ts
type ActionResult<
Success extends Record<string, unknown> | undefined = Record<string, any>,
Invalid extends Record<string, unknown> | undefined = Record<string, any>
> =
| { type: 'success'; status: number; data?: Success }
| { type: 'invalid'; status: number; data?: Invalid }
| { type: 'redirect'; status: number; location: string }
| { type: 'error'; error: any };

Actions

Shape of the export const actions = {..} object in +page.server.js. See form actions for more information.

ts
type Actions<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
OutputData extends Record<string, any> | void = Record<string, any> | void,
RouteId extends string | null = string | null
> = Record<string, Action<Params, OutputData, RouteId>>;

Adapter

Adapters are responsible for taking the production build and turning it into something that can be deployed to a platform of your choosing.

ts
interface Adapter {}
ts
name: string;

The name of the adapter, using for logging. Will typically correspond to the package name.

ts
adapt(builder: Builder): MaybePromise<void>;
  • builder An object provided by SvelteKit that contains methods for adapting the app

This function is called after SvelteKit has built your app.

AfterNavigate

The argument passed to afterNavigate callbacks.

ts
interface AfterNavigate extends Navigation {}
ts
type: Omit<NavigationType, 'leave'>;

The type of navigation:

  • enter: The app has hydrated
  • form: The user submitted a <form>
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
willUnload: false;

Since afterNavigate is called after a navigation completes, it will never be called with a navigation that unloads the page.

AwaitedActions

ts
type AwaitedActions<T extends Record<string, (...args: any) => any>> = {
[Key in keyof T]: OptionalUnion<
UnpackValidationError<Awaited<ReturnType<T[Key]>>>
>;
}[keyof T];

AwaitedProperties

ts
type AwaitedProperties<input extends Record<string, any> | void> =
AwaitedPropertiesUnion<input> extends Record<string, any>
? OptionalUnion<AwaitedPropertiesUnion<input>>
: AwaitedPropertiesUnion<input>;

BeforeNavigate

The argument passed to beforeNavigate callbacks.

ts
interface BeforeNavigate extends Navigation {}
ts
cancel(): void;

Call this to prevent the navigation from starting.

Builder

This object is passed to the adapt function of adapters. It contains various methods and properties that are useful for adapting the app.

ts
interface Builder {}
ts
log: Logger;

Print messages to the console. log.info and log.minor are silent unless Vite's logLevel is info.

ts
rimraf(dir: string): void;

Remove dir and all its contents.

ts
mkdirp(dir: string): void;

Create dir and any required parent directories.

ts
config: ValidatedConfig;

The fully resolved svelte.config.js.

ts
prerendered: Prerendered;

Information about prerendered pages and assets, if any.

ts
createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
  • fn A function that groups a set of routes into an entry point

Create separate functions that map to one or more routes of your app.

ts
generateManifest(opts: { relativePath: string }): string;
  • opts a relative path to the base directory of the app and optionally in which format (esm or cjs) the manifest should be generated

Generate a server-side manifest to initialise the SvelteKit server with.

ts
getBuildDirectory(name: string): string;
  • name path to the file, relative to the build directory

Resolve a path to the name directory inside outDir, e.g. /path/to/.svelte-kit/my-adapter.

ts
getClientDirectory(): string;

Get the fully resolved path to the directory containing client-side assets, including the contents of your static directory.

ts
getServerDirectory(): string;

Get the fully resolved path to the directory containing server-side code.

ts
getAppPath(): string;

Get the application path including any configured base path, e.g. /my-base-path/_app.

ts
writeClient(dest: string): string[];
  • dest the destination folder
  • returns an array of files written to dest

Write client assets to dest.

ts
writePrerendered(
dest: string,
opts?: {
fallback?: string;
}
): string[];
  • dest the destination folder
  • opts.fallback the name of a file for fallback responses, like 200.html or 404.html depending on where the app is deployed
  • returns an array of files written to dest

Write prerendered files to dest.

ts
writeServer(dest: string): string[];
  • dest the destination folder
  • returns an array of files written to dest

Write server-side code to dest.

ts
copy(
from: string,
to: string,
opts?: {
filter?(basename: string): boolean;
replace?: Record<string, string>;
}
): string[];
  • from the source file or directory
  • to the destination file or directory
  • opts.filter a function to determine whether a file or directory should be copied
  • opts.replace a map of strings to replace
  • returns an array of files that were copied

Copy a file or directory.

ts
compress(directory: string): Promise<void>;
  • directory The directory containing the files to be compressed

Compress files in directory with gzip and brotli, where appropriate. Generates .gz and .br files alongside the originals.

Config

ts
interface Config {}

See the configuration reference for details.

Cookies

ts
interface Cookies {}
ts
get(name: string, opts?: import('cookie').CookieParseOptions): string | undefined;
  • name the name of the cookie
  • opts the options, passed directly to cookie.parse. See documentation here

事前に cookies.set で設定された cookie や、またはリクエストヘッダーから cookie を取得します。

ts
set(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): void;
  • name the name of the cookie
  • value the cookie value
  • opts the options, passed directory to cookie.serialize. See documentation here

cookie を設定します。これはレスポンスに set-cookie ヘッダーを追加し、また、現在のリクエスト中に cookies.get を通じてその cookie を利用可能にします。

httpOnlysecure オプションはデフォルトで true となっており (http://localhost の場合は例外として securefalse です)、クライアントサイドの JavaScript で cookie を読み取ったり、HTTP 上で送信したりしたい場合は、明示的に無効にする必要があります。sameSite オプションのデフォルトは lax です。

デフォルトでは、cookie の path は 現在のパス名の 'directory' です。ほとんどの場合、cookie をアプリ全体で利用可能にするには明示的に path: '/' を設定する必要があります。

ts
delete(name: string, opts?: import('cookie').CookieSerializeOptions): void;
  • name the name of the cookie
  • opts the options, passed directory to cookie.serialize. The path must match the path of the cookie you want to delete. See documentation here

値に空文字列(empty string)を設定したり、有効期限(expiry date)を過去に設定することで、cookie を削除します。

By default, the path of a cookie is the 'directory' of the current pathname. In most cases you should explicitly set path: '/' to make the cookie available throughout your app.

ts
serialize(name: string, value: string, opts?: import('cookie').CookieSerializeOptions): string;
  • name the name of the cookie
  • value the cookie value
  • opts the options, passed directory to cookie.serialize. See documentation here

cookie の名前と値のペアを Set-Cookie ヘッダー文字列にシリアライズします。ただし、それをレスポンスに適用しないでください。

httpOnlysecure オプションはデフォルトで true となっており (http://localhost の場合は例外として securefalse です)、クライアントサイドの JavaScript で cookie を読み取ったり、HTTP 上で送信したりしたい場合は、明示的に無効にする必要があります。sameSite オプションのデフォルトは lax です。

デフォルトでは、cookie の path は 現在のパス名です。ほとんどの場合、cookie をアプリ全体で利用可能にするには明示的に path: '/' を設定する必要があります。

Handle

The handle hook runs every time the SvelteKit server receives a request and determines the response. It receives an event object representing the request and a function called resolve, which renders the route and generates a Response. This allows you to modify response headers or bodies, or bypass SvelteKit entirely (for implementing routes programmatically, for example).

ts
interface Handle {}
ts
(input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<Response>;

HandleClientError

The client-side handleError hook runs when an unexpected error is thrown while navigating.

If an unexpected error is thrown during loading or the following render, this function will be called with the error and the event. Make sure that this function never throws an error.

ts
interface HandleClientError {}
ts
(input: { error: unknown; event: NavigationEvent }): MaybePromise<void | App.Error>;

HandleFetch

The handleFetch hook allows you to modify (or replace) a fetch request that happens inside a load function that runs on the server (or during pre-rendering)

ts
interface HandleFetch {}
ts
(input: { event: RequestEvent; request: Request; fetch: typeof fetch }): MaybePromise<Response>;

HandleServerError

The server-side handleError hook runs when an unexpected error is thrown while responding to a request.

If an unexpected error is thrown during loading or rendering, this function will be called with the error and the event. Make sure that this function never throws an error.

ts
interface HandleServerError {}
ts
(input: { error: unknown; event: RequestEvent }): MaybePromise<void | App.Error>;

HttpError

error 関数に返されるオブジェクトです

ts
interface HttpError {}
ts
status: number;

The HTTP status code, in the range 400-599

ts
body: App.Error;

The content of the error.

KitConfig

ts
interface KitConfig {}

See the configuration reference for details.

Load

PageLoadLayoutLoad のジェネリックなフォームです。Load を直接使用するのではなく、./$types (generated types 参照) から インポートしてください。

ts
interface 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<string, any>,
OutputData extends Record<string, unknown> | void = Record<
string,
any
> | void,
RouteId extends string | null = string | null
> {}
ts
(event: LoadEvent<Params, InputData, ParentData, RouteId>): MaybePromise<OutputData>;

LoadEvent

The generic form of PageLoadEvent and LayoutLoadEvent. You should import those from ./$types (see generated types) rather than using LoadEvent directly.

ts
interface LoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
Data extends Record<string, unknown> | null = Record<string, any> | null,
ParentData extends Record<string, unknown> = Record<string, any>,
RouteId extends string | null = string | null
> extends NavigationEvent<Params, RouteId> {}
ts
fetch: typeof fetch;

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. 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

Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.

ts
data: Data;

Contains the data returned by the route's server load function (in +layout.server.js or +page.server.js), if any.

ts
setHeaders(headers: Record<string, string>): void;

If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:

ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
 
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
 
return response.json();
}

Setting the same header multiple times (even in separate load functions) is an error — you can only set a given header once.

You cannot add a set-cookie header with setHeaders — use the cookies API in a server-only load function instead.

setHeaders has no effect when a load function runs in the browser.

ts
parent(): Promise<ParentData>;

await parent() returns data from parent +layout.js load functions. Implicitly, a missing +layout.js is treated as a ({ data }) => data function, meaning that it will return and forward data from parent +layout.server.js files.

Be careful not to introduce accidental waterfalls when using await parent(). If for example you only want to merge parent data into the returned output, call it after fetching your other data.

ts
depends(...deps: string[]): void;

This function declares that the load function has a dependency on one or more URLs or custom identifiers, which can subsequently be used with invalidate() to cause load to rerun.

Most of the time you won't need this, as fetch calls depends on your behalf — it's only necessary if you're using a custom API client that bypasses fetch.

URLs can be absolute or relative to the page being loaded, and must be encoded.

Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.

The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.

ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
 
return { count: count++ };
}
// @errors: 7031
<script>
  import { invalidate } from '$app/navigation';

  export let data;

  const increase = async () => {
    await invalidate('increase:count');
  }
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>

Navigation

ts
interface Navigation {}
ts
from: NavigationTarget | null;

Where navigation was triggered from

ts
to: NavigationTarget | null;

Where navigation is going to/has gone to

ts
type: Omit<NavigationType, 'enter'>;

The type of navigation:

  • form: The user submitted a <form>
  • leave: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
willUnload: boolean;

Whether or not the navigation will result in the page being unloaded (i.e. not a client-side navigation)

ts
delta?: number;

In case of a history back/forward navigation, the number of steps to go back/forward

NavigationEvent

ts
interface NavigationEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
params: Params;

The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object

ts
route: {}

Info about the current route

ts
id: RouteId;

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

ts
url: URL;

The URL of the current page

NavigationTarget

Information about the target of a specific navigation.

ts
interface NavigationTarget {}
ts
params: Record<string, string> | null;

Parameters of the target page - e.g. for a route like /blog/[slug], a { slug: string } object. Is null if the target is not part of the SvelteKit app (could not be resolved to a route).

ts
route: { id: string | null };

Info about the target route

ts
url: URL;

The URL that is navigated to

NavigationType

  • enter: The app has hydrated
  • form: The user submitted a <form>
  • leave: The user is leaving the app by closing the tab or using the back/forward buttons to go to a different document
  • link: Navigation was triggered by a link click
  • goto: Navigation was triggered by a goto(...) call or a redirect
  • popstate: Navigation was triggered by back/forward navigation
ts
type NavigationType = 'enter' | 'form' | 'leave' | 'link' | 'goto' | 'popstate';

Page

The shape of the $page store

ts
interface Page<
Params extends Record<string, string> = Record<string, string>,
RouteId extends string | null = string | null
> {}
ts
url: URL;

The URL of the current page

ts
params: Params;

The parameters of the current page - e.g. for a route like /blog/[slug], a { slug: string } object

ts
route: {}

Info about the current route

ts
id: RouteId;

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

ts
status: number;

Http status code of the current page

ts
error: App.Error | null;

The error object of the current page, if any. Filled from the handleError hooks.

ts
data: App.PageData & Record<string, any>;

The merged result of all data from all load functions on the current page. You can type a common denominator through App.PageData.

ts
form: any;

Filled only after a form submission. See form actions for more info.

ParamMatcher

The shape of a param matcher. See matching for more info.

ts
interface ParamMatcher {}
ts
(param: string): boolean;

Redirect

redirect 関数に返されるオブジェクトです

ts
interface Redirect {}
ts
status: 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308;

The HTTP status code, in the range 300-308.

ts
location: string;

The location to redirect to.

RequestEvent

ts
interface RequestEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
cookies: Cookies;

Get or set cookies related to the current request

ts
fetch: typeof fetch;

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

Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.

ts
getClientAddress(): string;

The client's IP address, set by the adapter.

ts
locals: App.Locals;

Contains custom data that was added to the request within the handle hook.

ts
params: Params;

The parameters of the current page or endpoint - e.g. for a route like /blog/[slug], a { slug: string } object

ts
platform: Readonly<App.Platform>;

Additional data made available through the adapter.

ts
request: Request;

The original request object

ts
route: {}

Info about the current route

ts
id: RouteId;

The ID of the current route - e.g. for src/routes/blog/[slug], it would be /blog/[slug]

ts
setHeaders(headers: Record<string, string>): void;

If you need to set headers for the response, you can do so using the this method. This is useful if you want the page to be cached, for example:

ts
export async function load({ fetch, setHeaders }) {
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
7031
7031
Binding element 'fetch' implicitly has an 'any' type.
Binding element 'setHeaders' implicitly has an 'any' type.
const url = `https://cms.example.com/articles.json`;
const response = await fetch(url);
 
setHeaders({
age: response.headers.get('age'),
'cache-control': response.headers.get('cache-control')
});
 
return response.json();
}

Setting the same header multiple times (even in separate load functions) is an error — you can only set a given header once.

You cannot add a set-cookie header with setHeaders — use the cookies API instead.

ts
url: URL;

The URL of the current page or endpoint

RequestHandler

(event: RequestEvent) => Response という関数で、+server.js ファイルからエクスポートされます。HTTP verb (GET, PUT, PATCH, etc) に対応しており、それぞれの HTTP メソッドのリクエストを処理します。

1つめのジェネリックな引数(first generic argument)として Params を受け取りますが、代わりに generated types を使うことでこれをスキップすることができます。

ts
interface RequestHandler<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
(event: RequestEvent<Params, RouteId>): MaybePromise<Response>;

ResolveOptions

ts
interface ResolveOptions {}
ts
transformPageChunk?(input: { html: string; done: boolean }): MaybePromise<string | undefined>;
  • input the html chunk and the info if this is the last chunk

Applies custom transforms to HTML. If done is true, it's the final chunk. Chunks are not guaranteed to be well-formed HTML (they could include an element's opening tag but not its closing tag, for example) but they will always be split at sensible boundaries such as %sveltekit.head% or layout/page components.

ts
filterSerializedResponseHeaders?(name: string, value: string): boolean;
  • name header name
  • value header value

Determines which headers should be included in serialized responses when a load function loads a resource with fetch. By default, none will be included.

ts
preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean;
  • input the type of the file and its path

Determines what should be added to the <head> tag to preload it. By default, js, css and font files will be preloaded.

SSRManifest

ts
interface SSRManifest {}
ts
appDir: string;
ts
appPath: string;
ts
assets: Set<string>;
ts
mimeTypes: Record<string, string>;
ts
_: {
entry: {
file: string;
imports: string[];
stylesheets: string[];
fonts: string[];
};
nodes: SSRNodeLoader[];
routes: SSRRoute[];
matchers(): Promise<Record<string, ParamMatcher>>;
};

private fields

Server

ts
class Server {
constructor(manifest: SSRManifest);
init(options: ServerInitOptions): Promise<void>;
respond(request: Request, options: RequestOptions): Promise<Response>;
}

ServerInitOptions

ts
interface ServerInitOptions {}
ts
env: Record<string, string>;

ServerLoad

PageServerLoadLayoutServerLoad のジェネリックなフォームです。ServerLoad を直接使用するのではなく、./$types (generated types を参照) から インポートしてください。

ts
interface 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 = Record<string, any> | void,
RouteId extends string | null = string | null
> {}
ts
(event: ServerLoadEvent<Params, ParentData, RouteId>): MaybePromise<OutputData>;

ServerLoadEvent

ts
interface ServerLoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
ParentData extends Record<string, any> = Record<string, any>,
RouteId extends string | null = string | null
> extends RequestEvent<Params, RouteId> {}
ts
parent(): Promise<ParentData>;

await parent() returns data from parent +layout.server.js load functions.

Be careful not to introduce accidental waterfalls when using await parent(). If for example you only want to merge parent data into the returned output, call it after fetching your other data.

ts
depends(...deps: string[]): void;

This function declares that the load function has a dependency on one or more URLs or custom identifiers, which can subsequently be used with invalidate() to cause load to rerun.

Most of the time you won't need this, as fetch calls depends on your behalf — it's only necessary if you're using a custom API client that bypasses fetch.

URLs can be absolute or relative to the page being loaded, and must be encoded.

Custom identifiers have to be prefixed with one or more lowercase letters followed by a colon to conform to the URI specification.

The following example shows how to use depends to register a dependency on a custom identifier, which is invalidated after a button click, making the load function rerun.

ts
let count = 0;
export async function load({ depends }) {
Binding element 'depends' implicitly has an 'any' type.7031Binding element 'depends' implicitly has an 'any' type.
depends('increase:count');
 
return { count: count++ };
}
// @errors: 7031
<script>
  import { invalidate } from '$app/navigation';

  export let data;

  const increase = async () => {
    await invalidate('increase:count');
  }
</script>

<p>{data.count}<p>
<button on:click={increase}>Increase Count</button>

SubmitFunction

ts
interface SubmitFunction<
Success extends Record<string, unknown> | undefined = Record<string, any>,
Invalid extends Record<string, unknown> | undefined = Record<string, any>
> {}
ts
(input: {
action: URL;
data: FormData;
form: HTMLFormElement;
controller: AbortController;
cancel(): void;
| void
| ((opts: {
form: HTMLFormElement;
action: URL;
result: ActionResult<Success, Invalid>;
/**
* Call this to get the default behavior of a form submission response.
* @param options Set `reset: false` if you don't want the `<form>` values to be reset after a successful submission.
*/
update(options?: { reset: boolean }): Promise<void>;
}) => void)
>;

ValidationError

The object returned by the invalid function

ts
interface ValidationError<
T extends Record<string, unknown> | undefined = undefined
> extends UniqueInterface {}
ts
status: number;
ts
data: T;

Private types

The following are referenced by the public types documented above, but cannot be imported directly:

AdapterEntry

ts
interface AdapterEntry {}
ts
id: string;

A string that uniquely identifies an HTTP service (e.g. serverless function) and is used for deduplication. For example, /foo/a-[b] and /foo/[c] are different routes, but would both be represented in a Netlify _redirects file as /foo/:param, so they share an ID

ts
filter(route: RouteDefinition): boolean;

A function that compares the candidate route with the current route to determine if it should be treated as a fallback for the current route. For example, /foo/[c] is a fallback for /foo/a-[b], and /[...catchall] is a fallback for all routes

ts
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;

A function that is invoked once the entry has been created. This is where you should write the function to the filesystem and generate redirect manifests.

Csp

ts
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| 'wasm-unsafe-eval'
| 'none';
type CryptoSource = `${'nonce' | 'sha256' | 'sha384' | 'sha512'}-${string}`;
type FrameSource = HostSource | SchemeSource | 'self' | 'none';
type HostNameScheme = `${string}.${string}` | 'localhost';
type HostSource = `${HostProtocolSchemes}${HostNameScheme}${PortScheme}`;
type HostProtocolSchemes = `${string}://` | '';
type HttpDelineator = '/' | '?' | '#' | '\\';
type PortScheme = `:${number}` | '' | ':*';
type SchemeSource =
| 'http:'
| 'https:'
| 'data:'
| 'mediastream:'
| 'blob:'
| 'filesystem:';
type Source = HostSource | SchemeSource | CryptoSource | BaseSource;
type Sources = Source[];
type UriPath = `${HttpDelineator}${string}`;
}

CspDirectives

ts
interface CspDirectives {}
ts
'child-src'?: Csp.Sources;
ts
'default-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'frame-src'?: Csp.Sources;
ts
'worker-src'?: Csp.Sources;
ts
'connect-src'?: Csp.Sources;
ts
'font-src'?: Csp.Sources;
ts
'img-src'?: Csp.Sources;
ts
'manifest-src'?: Csp.Sources;
ts
'media-src'?: Csp.Sources;
ts
'object-src'?: Csp.Sources;
ts
'prefetch-src'?: Csp.Sources;
ts
'script-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'script-src-elem'?: Csp.Sources;
ts
'script-src-attr'?: Csp.Sources;
ts
'style-src'?: Array<Csp.Source | Csp.ActionSource>;
ts
'style-src-elem'?: Csp.Sources;
ts
'style-src-attr'?: Csp.Sources;
ts
'base-uri'?: Array<Csp.Source | Csp.ActionSource>;
ts
sandbox?: Array<
| 'allow-downloads-without-user-activation'
| 'allow-forms'
| 'allow-modals'
| 'allow-orientation-lock'
| 'allow-pointer-lock'
| 'allow-popups'
| 'allow-popups-to-escape-sandbox'
| 'allow-presentation'
| 'allow-same-origin'
| 'allow-scripts'
| 'allow-storage-access-by-user-activation'
| 'allow-top-navigation'
| 'allow-top-navigation-by-user-activation'
>;
ts
'form-action'?: Array<Csp.Source | Csp.ActionSource>;
ts
'frame-ancestors'?: Array<Csp.HostSource | Csp.SchemeSource | Csp.FrameSource>;
ts
'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;
ts
'report-uri'?: Csp.UriPath[];
ts
'report-to'?: string[];
ts
'require-trusted-types-for'?: Array<'script'>;
ts
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
ts
'upgrade-insecure-requests'?: boolean;
ts
'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
ts
'block-all-mixed-content'?: boolean;
ts
'plugin-types'?: Array<`${string}/${string}` | 'none'>;
ts
referrer?: Array<
| 'no-referrer'
| 'no-referrer-when-downgrade'
| 'origin'
| 'origin-when-cross-origin'
| 'same-origin'
| 'strict-origin'
| 'strict-origin-when-cross-origin'
| 'unsafe-url'
| 'none'
>;

HttpMethod

ts
type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';

Logger

ts
interface Logger {}
ts
(msg: string): void;
ts
success(msg: string): void;
ts
error(msg: string): void;
ts
warn(msg: string): void;
ts
minor(msg: string): void;
ts
info(msg: string): void;

MaybePromise

ts
type MaybePromise<T> = T | Promise<T>;

PrerenderHttpErrorHandler

ts
interface PrerenderHttpErrorHandler {}
ts
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
}): void;

PrerenderHttpErrorHandlerValue

ts
type PrerenderHttpErrorHandlerValue =
| 'fail'
| 'warn'
| 'ignore'

PrerenderMap

ts
type PrerenderMap = Map<string, PrerenderOption>;

PrerenderMissingIdHandler

ts
interface PrerenderMissingIdHandler {}
ts
(details: { path: string; id: string; referrers: string[] }): void;

PrerenderMissingIdHandlerValue

ts
type PrerenderMissingIdHandlerValue =
| 'fail'
| 'warn'
| 'ignore'

PrerenderOption

ts
type PrerenderOption = boolean | 'auto';

Prerendered

ts
interface Prerendered {}
ts
pages: Map<
string,
{
/** The location of the .html file relative to the output directory */
file: string;
}
>;

A map of path to { file } objects, where a path like /foo corresponds to foo.html and a path like /bar/ corresponds to bar/index.html.

ts
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;

A map of path to { type } objects.

ts
redirects: Map<
string,
{
status: number;
location: string;
}
>;

A map of redirects encountered during prerendering.

ts
paths: string[];

An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config)

RequestOptions

ts
interface RequestOptions {}
ts
getClientAddress(): string;
ts
platform?: App.Platform;

RouteDefinition

ts
interface RouteDefinition {}
ts
id: string;
ts
pattern: RegExp;
ts
segments: RouteSegment[];
ts
methods: HttpMethod[];

RouteSegment

ts
interface RouteSegment {}
ts
content: string;
ts
dynamic: boolean;
ts
rest: boolean;

TrailingSlash

ts
type TrailingSlash = 'never' | 'always' | 'ignore';

UniqueInterface

ts
interface UniqueInterface {}
ts
readonly [uniqueSymbol]: unknown;

Generated types

RequestHandlerLoad の型はどちらも Params 引数を受け取りますが、その params オブジェクトに型を付けることができます。例えば、このエンドポイントは foobarbaz が渡されることを想定しています:

ts
/** @type {import('@sveltejs/kit').RequestHandler<{
* foo: string;
* bar: string;
* baz: string
* }>} */
export async function GET({ params }) {
A function whose declared type is neither 'void' nor 'any' must return a value.2355A function whose declared type is neither 'void' nor 'any' must return a value.
// ...
}
ts
import type { RequestHandler } from '@sveltejs/kit';
 
export const GET: RequestHandler = async ({ params }) => {
Type '({ params }: RequestEvent<Partial<Record<string, string>>, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<Partial<Record<string, string>>, string | null>'. Type 'Promise<void>' is not assignable to type 'MaybePromise<Response>'. Type 'Promise<void>' is not assignable to type 'Promise<Response>'. Type 'void' is not assignable to type 'Response'.2322Type '({ params }: RequestEvent<Partial<Record<string, string>>, string | null>) => Promise<void>' is not assignable to type 'RequestHandler<Partial<Record<string, string>>, string | null>'. Type 'Promise<void>' is not assignable to type 'MaybePromise<Response>'. Type 'Promise<void>' is not assignable to type 'Promise<Response>'. Type 'void' is not assignable to type 'Response'.
// ...
}

言うまでもなく、これを書くのは面倒で、移植性も低いです ([foo] ディレクトリを [qux] にリネームした場合、この型は実態を反映していないものとなります)。

この問題を解決するため、SvelteKit は各エンドポイント、各ページごとに .d.ts ファイルを生成します:

ts
import type * as Kit from '@sveltejs/kit';
 
type RouteParams = {
foo: string;
bar: string;
baz: string;
}
 
export type PageServerLoad = Kit.ServerLoad<RouteParams>;
export type PageLoad = Kit.Load<RouteParams>;

TypeScript の設定にある rootDirs オプションのおかげで、エンドポイントとページではこれらのファイルが同じディレクトリにあるかのようにインポートすることができます:

ts
/** @type {import('./$types').PageServerLoad} */
export async function GET({ params }) {
// ...
}
ts
import type { PageServerLoad } from './$types';
 
export const GET: PageServerLoad = async ({ params }) => {
// ...
}
ts
/** @type {import('./$types').PageLoad} */
export async function load({ params, fetch }) {
// ...
}
ts
import type { PageLoad } from './$types';
 
export const load: PageLoad = async ({ params, fetch }) => {
// ...
}

これを動作させるためには、tsconfig.json または jsconfig.json が生成された .svelte-kit/tsconfig.json を継承する必要があります (.svelte-kit の場所は outDir です):

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

Default 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": {
    // 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"
  }
}

App

App namespace を宣言することで、アプリ内のオブジェクトを型付けする方法を SvelteKit に伝えることが可能です。デフォルトでは、新しいプロジェクトには src/app.d.ts というファイルがあり、以下の内容を含んでいます:

ts
/// <reference types="@sveltejs/kit" />
 
declare namespace App {
interface Error {}
interface Locals {}
interface PageData {}
interface Platform {}
}

これらのインターフェースを作成することによって、event.localsevent.platformload 関数の data を使用する際に型の安全性を確保することができます。

アンビエント宣言(ambient declaration)ファイルであるため、import 文を使用するときには注意が必要です。import を トップレベルに追加すると、宣言ファイル (declaration file) はアンビエント (ambient) とはみなされなくなるため、他のファイルでこれらの型付けにアクセスできなくなります。 これを避けるには、import(...) 関数をお使いください:

ts
interface Locals {
user: import('$lib/types').User;
}

Or wrap the namespace with declare global:

ts
import { User } from '$lib/types';
 
declare global {
namespace App {
interface Locals {
user: User;
}
// ...
}
}

Error

想定されるエラーと予期せぬエラーの共通の形を定義します。想定されるエラーは error 関数を使用してスローされます。予期せぬエラーは handleError hooks で処理され、この形を返す必要があります。

ts
interface Error {}
ts
message: string;

Locals

event.locals を定義する interface です。event.localshooks (handlehandleError)、load 関数(サーバーのみ)、+server.js ファイルからアクセスできます。

ts
interface Locals {}

PageData

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

ts
interface PageData {}

Platform

adapter が event.platformプラットフォーム固有の情報 を提供する場合、ここでそれを指定することができます。

ts
interface Platform {}