Skip to main content

Types

Edit this page on GitHub

Public typespermalink

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

Actionpermalink

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

ActionResultpermalink

When calling a form action via fetch, the response will be one of these shapes.

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 };

Actionspermalink

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

Adapterpermalink

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

AfterNavigatepermalink

The argument passed to afterNavigate callbacks.

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

AwaitedActionspermalink

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

AwaitedPropertiespermalink

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

BeforeNavigatepermalink

The argument passed to beforeNavigate callbacks.

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

Builderpermalink

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;
ts
rimraf(dir: string): void;
ts
mkdirp(dir: string): void;
ts
config: ValidatedConfig;
ts
prerendered: Prerendered;
ts
createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
  • fn A function that groups a set of routes into an entry point
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
ts
getBuildDirectory(name: string): string;
  • name path to the file, relative to the build directory
ts
getClientDirectory(): string;
ts
getServerDirectory(): string;
ts
getAppPath(): string;
ts
writeClient(dest: string): string[];
  • dest the destination folder
  • returns an array of files written 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
ts
writeServer(dest: string): string[];
  • dest the destination folder
  • returns an array of files written 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
ts
compress(directory: string): Promise<void>;
  • directory The directory containing the files to be compressed

Configpermalink

ts
interface Config {}

See the configuration reference for details.

Cookiespermalink

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

Handlepermalink

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

HandleClientErrorpermalink

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

HandleFetchpermalink

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

HandleServerErrorpermalink

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

HttpErrorpermalink

The object returned by the error function.

ts
interface HttpError {}
ts
status: number;
ts
body: App.Error;

KitConfigpermalink

ts
interface KitConfig {}

See the configuration reference for details.

Loadpermalink

The generic form of PageLoad and LayoutLoad. You should import those from ./$types (see generated types) rather than using Load directly.

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

LoadEventpermalink

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;
ts
data: Data;
ts
setHeaders(headers: Record<string, string>): void;
ts
parent(): Promise<ParentData>;
ts
depends(...deps: string[]): void;

Navigationpermalink

ts
interface Navigation {}
ts
from: NavigationTarget | null;
ts
to: NavigationTarget | null;
ts
type: Omit<NavigationType, 'enter'>;
ts
willUnload: boolean;
ts
delta?: number;

NavigationEventpermalink

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

NavigationTargetpermalink

Information about the target of a specific navigation.

ts
interface NavigationTarget {}
ts
params: Record<string, string> | null;
ts
route: { id: string | null };
ts
url: URL;

NavigationTypepermalink

  • enter: The app has hydrated
  • 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' | 'leave' | 'link' | 'goto' | 'popstate';

Pagepermalink

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;
ts
params: Params;
ts
route: {}
ts
id: RouteId;
ts
status: number;
ts
error: App.Error | null;
ts
data: App.PageData & Record<string, any>;
ts
form: any;

ParamMatcherpermalink

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

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

Redirectpermalink

The object returned by the redirect function

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

RequestEventpermalink

ts
interface RequestEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
RouteId extends string | null = string | null
> {}
ts
cookies: Cookies;
ts
fetch: typeof fetch;
ts
getClientAddress(): string;
ts
locals: App.Locals;
ts
params: Params;
ts
platform: Readonly<App.Platform>;
ts
request: Request;
ts
route: {}
ts
id: RouteId;
ts
setHeaders(headers: Record<string, string>): void;
ts
url: URL;

RequestHandlerpermalink

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.

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

ResolveOptionspermalink

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
ts
filterSerializedResponseHeaders?(name: string, value: string): boolean;
  • name header name
  • value header value
ts
preload?(input: { type: 'font' | 'css' | 'js' | 'asset'; path: string }): boolean;
  • input the type of the file and its path

SSRManifestpermalink

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>>;
};

Serverpermalink

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

ServerInitOptionspermalink

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

ServerLoadpermalink

The generic form of PageServerLoad and LayoutServerLoad. You should import those from ./$types (see generated types) rather than using ServerLoad directly.

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

ServerLoadEventpermalink

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>;
ts
depends(...deps: string[]): void;

SubmitFunctionpermalink

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)
>;

ValidationErrorpermalink

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 typespermalink

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

AdapterEntrypermalink

ts
interface AdapterEntry {}
ts
id: string;
ts
filter(route: RouteDefinition): boolean;
ts
complete(entry: { generateManifest(opts: { relativePath: string }): string }): MaybePromise<void>;

Csppermalink

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}`;
}

CspDirectivespermalink

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'
>;

HttpMethodpermalink

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

Loggerpermalink

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;

MaybePromisepermalink

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

PrerenderHttpErrorHandlerpermalink

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

PrerenderHttpErrorHandlerValuepermalink

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

PrerenderMappermalink

ts
type PrerenderMap = Map<string, PrerenderOption>;

PrerenderMissingIdHandlerpermalink

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

PrerenderMissingIdHandlerValuepermalink

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

PrerenderOptionpermalink

ts
type PrerenderOption = boolean | 'auto';

Prerenderedpermalink

ts
interface Prerendered {}
ts
pages: Map<
string,
{
/** The location of the .html file relative to the output directory */
file: string;
}
>;
ts
assets: Map<
string,
{
/** The MIME type of the asset */
type: string;
}
>;
ts
redirects: Map<
string,
{
status: number;
location: string;
}
>;
ts
paths: string[];

RequestOptionspermalink

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

RouteDefinitionpermalink

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

RouteSegmentpermalink

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

TrailingSlashpermalink

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

UniqueInterfacepermalink

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

Generated typespermalink

The RequestHandler and Load types both accept a Params argument allowing you to type the params object. For example this endpoint expects foo, bar and baz params:

src/routes/[foo]/[bar]/[baz]/+page.server.js
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.
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.server.ts
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'.
// ...
}

Needless to say, this is cumbersome to write out, and less portable (if you were to rename the [foo] directory to [qux], the type would no longer reflect reality).

To solve this problem, SvelteKit generates .d.ts files for each of your endpoints and pages:

.svelte-kit/types/src/routes/[foo]/[bar]/[baz]/$types.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>;

These files can be imported into your endpoints and pages as siblings, thanks to the rootDirs option in your TypeScript configuration:

src/routes/[foo]/[bar]/[baz]/+page.server.js
ts
/** @type {import('./$types').PageServerLoad} */
export async function GET({ params }) {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.server.ts
ts
import type { PageServerLoad } from './$types';
 
export const GET: PageServerLoad = async ({ params }) => {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.js
ts
/** @type {import('./$types').PageLoad} */
export async function load({ params, fetch }) {
// ...
}
src/routes/[foo]/[bar]/[baz]/+page.ts
ts
import type { PageLoad } from './$types';
 
export const load: PageLoad = async ({ params, fetch }) => {
// ...
}

For this to work, your own tsconfig.json or jsconfig.json should extend from the generated .svelte-kit/tsconfig.json (where .svelte-kit is your outDir):

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

Default tsconfig.jsonpermalink

The generated .svelte-kit/tsconfig.json file contains a mixture of options. Some are generated programmatically based on your project configuration, and should generally not be overridden without good reason:

.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/**", "./**"]
}

Others are required for SvelteKit to work properly, and should also be left untouched unless you know what you're doing:

.svelte-kit/tsconfig.json
{
  "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"
  }
}

Apppermalink

It's possible to tell SvelteKit how to type objects inside your app by declaring the App namespace. By default, a new project will have a file called src/app.d.ts containing the following:

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

By populating these interfaces, you will gain type safety when using event.locals, event.platform, and data from load functions.

Note that since it's an ambient declaration file, you have to be careful when using import statements. Once you add an import at the top level, the declaration file is no longer considered ambient and you lose access to these typings in other files. To avoid this, either use the import(...) function:

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;
}
// ...
}
}

Errorpermalink

Defines the common shape of expected and unexpected errors. Expected errors are thrown using the error function. Unexpected errors are handled by the handleError hooks which should return this shape.

ts
interface Error {}
ts
message: string;

Localspermalink

The interface that defines event.locals, which can be accessed in hooks (handle, and handleError), server-only load functions, and +server.js files.

ts
interface Locals {}

PageDatapermalink

Defines the common shape of the $page.data store - that is, the data that is shared between all pages. The Load and ServerLoad functions in ./$types will be narrowed accordingly. Use optional properties for data that is only present on specific pages. Do not add an index signature ([key: string]: any).

ts
interface PageData {}

Platformpermalink

If your adapter provides platform-specific context via event.platform, you can specify it here.

ts
interface Platform {}
We stand with Ukraine. Donate → We stand with Ukraine. Petition your leaders. Show your support.