Types
Edit this page on GitHub@sveltejs/kitpermalink
The following can be imported from @sveltejs/kit
:
Actionpermalink
interface Action<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>
> {
(event: RequestEvent<Params>): MaybePromise<
| { status?: number; errors: Record<string, any>; location?: never }
| { status?: never; errors?: never; location: string }
| void
>;
}
Adapterpermalink
interface Adapter {
name: string;
adapt(builder: Builder): MaybePromise<void>;
}
AwaitedErrorspermalink
type AwaitedErrors<T extends (...args: any) => any> = Awaited<
ReturnType<T>
> extends {
errors?: any;
}
? Awaited<ReturnType<T>>['errors']
: undefined;
AwaitedPropertiespermalink
type AwaitedProperties<input extends Record<string, any> | void> =
input extends void
? undefined // needs to be undefined, because void will break intellisense
: input extends Record<string, any>
? {
[key in keyof input]: Awaited<input[key]>;
}
: {} extends input // handles the any case
? input
: unknown;
Builderpermalink
interface Builder {
log: Logger;
rimraf(dir: string): void;
mkdirp(dir: string): void;
config: ValidatedConfig;
prerendered: Prerendered;
/** * Create entry points that map to individual functions * @param fn A function that groups a set of routes into an entry point */ createEntries(fn: (route: RouteDefinition) => AdapterEntry): Promise<void>;
generateManifest: (opts: {
relativePath: string;
format?: 'esm' | 'cjs';
}) => string;
getBuildDirectory(name: string): string;
getClientDirectory(): string;
getServerDirectory(): string;
getStaticDirectory(): string;
/** * @param dest the destination folder to which files should be copied * @returns an array of paths corresponding to the files that have been created by the copy */ writeClient(dest: string): string[];
/** * @param dest */ writePrerendered(
dest: string,
opts?: {
fallback?: string;
}
): string[];
/** * @param dest the destination folder to which files should be copied * @returns an array of paths corresponding to the files that have been created by the copy */ writeServer(dest: string): string[];
/** * @param from the source file or folder * @param to the destination file or folder * @param opts.filter a function to determine whether a file or folder should be copied * @param opts.replace a map of strings to replace * @returns an array of paths corresponding to the files that have been created by the copy */ copy(
from: string,
to: string,
opts?: {
filter?: (basename: string) => boolean;
replace?: Record<string, string>;
}
): string[];
/** * @param {string} directory Path to the directory containing the files to be compressed */ compress(directory: string): void;
}
Configpermalink
interface Config {
compilerOptions?: CompileOptions;
extensions?: string[];
kit?: KitConfig;
package?: {
source?: string;
dir?: string;
emitTypes?: boolean;
exports?: (filepath: string) => boolean;
files?: (filepath: string) => boolean;
};
preprocess?: any;
[key: string]: any;
}
ExternalFetchpermalink
interface ExternalFetch {
(req: Request): Promise<Response>;
}
Handlepermalink
interface Handle {
(input: {
event: RequestEvent;
resolve(event: RequestEvent, opts?: ResolveOptions): MaybePromise<Response>;
}): MaybePromise<Response>;
}
HandleErrorpermalink
interface HandleError {
(input: { error: Error & { frame?: string }; event: RequestEvent }): void;
}
KitConfigpermalink
interface KitConfig {
adapter?: Adapter;
alias?: Record<string, string>;
appDir?: string;
browser?: {
hydrate?: boolean;
router?: boolean;
};
csp?: {
mode?: 'hash' | 'nonce' | 'auto';
directives?: CspDirectives;
reportOnly?: CspDirectives;
};
env?: {
dir?: string;
publicPrefix?: string;
};
moduleExtensions?: string[];
files?: {
assets?: string;
hooks?: string;
lib?: string;
params?: string;
routes?: string;
serviceWorker?: string;
template?: string;
};
inlineStyleThreshold?: number;
methodOverride?: {
parameter?: string;
allowed?: string[];
};
outDir?: string;
paths?: {
assets?: string;
base?: string;
};
prerender?: {
concurrency?: number;
crawl?: boolean;
default?: boolean;
enabled?: boolean;
entries?: Array<'*' | `/${string}`>;
onError?: PrerenderOnErrorValue;
origin?: string;
};
serviceWorker?: {
register?: boolean;
files?: (filepath: string) => boolean;
};
trailingSlash?: TrailingSlash;
version?: {
name?: string;
pollInterval?: number;
};
}
Loadpermalink
The generic form of PageLoad
and LayoutLoad
. You should import those from ./$types
(see generated types)
rather than using Load
directly.
interface Load<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
InputData extends Record<string, any> | null = Record<string, any> | null,
ParentData extends Record<string, any> = Record<string, any>,
OutputData extends Record<string, any> | void = Record<string, any> | void
> {
(event: LoadEvent<Params, InputData, ParentData>): MaybePromise<OutputData>;
}
LoadEventpermalink
interface LoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
Data extends Record<string, any> | null = Record<string, any> | null,
ParentData extends Record<string, any> = Record<string, any>
> {
fetch(info: RequestInfo, init?: RequestInit): Promise<Response>;
params: Params;
data: Data;
routeId: string | null;
setHeaders: (headers: ResponseHeaders) => void;
url: URL;
parent: () => Promise<ParentData>;
depends: (...deps: string[]) => void;
}
Navigationpermalink
interface Navigation {
from: URL;
to: URL;
}
Pagepermalink
interface Page<Params extends Record<string, string> = Record<string, string>> {
url: URL;
params: Params;
routeId: string | null;
status: number;
error: HttpError | Error | null;
data: App.PageData & Record<string, any>;
}
ParamMatcherpermalink
interface ParamMatcher {
(param: string): boolean;
}
RequestEventpermalink
interface RequestEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>
> {
clientAddress: string;
locals: App.Locals;
params: Params;
platform: Readonly<App.Platform>;
request: Request;
routeId: string | null;
setHeaders: (headers: ResponseHeaders) => void;
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.
interface RequestHandler<
Params extends Record<string, string> = Record<string, string>
> {
(event: RequestEvent<Params>): MaybePromise<Response>;
}
ResolveOptionspermalink
interface ResolveOptions {
ssr?: boolean;
transformPageChunk?: (input: {
html: string;
done: boolean;
}) => MaybePromise<string | undefined>;
}
SSRManifestpermalink
interface SSRManifest {
appDir: string;
assets: Set<string>;
mimeTypes: Record<string, string>;
/** private fields */ _: {
entry: {
file: string;
imports: string[];
stylesheets: string[];
};
nodes: SSRNodeLoader[];
routes: SSRRoute[];
matchers: () => Promise<Record<string, ParamMatcher>>;
};
}
Serverpermalink
class Server {
constructor(manifest: SSRManifest);
init(options: ServerInitOptions): Promise<void>;
respond(request: Request, options: RequestOptions): Promise<Response>;
}
ServerInitOptionspermalink
interface ServerInitOptions {
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.
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
> {
(event: ServerLoadEvent<Params, ParentData>): MaybePromise<OutputData>;
}
ServerLoadEventpermalink
interface ServerLoadEvent<
Params extends Partial<Record<string, string>> = Partial<
Record<string, string>
>,
ParentData extends Record<string, any> = Record<string, any>
> extends RequestEvent<Params> {
parent: () => Promise<ParentData>;
}
Additional typespermalink
The following are referenced by the public types documented above, but cannot be imported directly:
AdapterEntrypermalink
interface AdapterEntry {
/** * 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 */ id: string;
/** * 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 */ filter: (route: RouteDefinition) => boolean;
/** * 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. */ complete: (entry: {
generateManifest: (opts: {
relativePath: string;
format?: 'esm' | 'cjs';
}) => string;
}) => MaybePromise<void>;
}
Csppermalink
namespace Csp {
type ActionSource = 'strict-dynamic' | 'report-sample';
type BaseSource =
| 'self'
| 'unsafe-eval'
| 'unsafe-hashes'
| 'unsafe-inline'
| '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
interface CspDirectives {
'child-src'?: Csp.Sources;
'default-src'?: Array<Csp.Source | Csp.ActionSource>;
'frame-src'?: Csp.Sources;
'worker-src'?: Csp.Sources;
'connect-src'?: Csp.Sources;
'font-src'?: Csp.Sources;
'img-src'?: Csp.Sources;
'manifest-src'?: Csp.Sources;
'media-src'?: Csp.Sources;
'object-src'?: Csp.Sources;
'prefetch-src'?: Csp.Sources;
'script-src'?: Array<Csp.Source | Csp.ActionSource>;
'script-src-elem'?: Csp.Sources;
'script-src-attr'?: Csp.Sources;
'style-src'?: Array<Csp.Source | Csp.ActionSource>;
'style-src-elem'?: Csp.Sources;
'style-src-attr'?: Csp.Sources;
'base-uri'?: Array<Csp.Source | Csp.ActionSource>;
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'
>;
'form-action'?: Array<Csp.Source | Csp.ActionSource>;
'frame-ancestors'?: Array<
Csp.HostSource | Csp.SchemeSource | Csp.FrameSource
>;
'navigate-to'?: Array<Csp.Source | Csp.ActionSource>;
'report-uri'?: Csp.UriPath[];
'report-to'?: string[];
'require-trusted-types-for'?: Array<'script'>;
'trusted-types'?: Array<'none' | 'allow-duplicates' | '*' | string>;
'upgrade-insecure-requests'?: boolean;
/** @deprecated */ 'require-sri-for'?: Array<'script' | 'style' | 'script style'>;
/** @deprecated */ 'block-all-mixed-content'?: boolean;
/** @deprecated */ 'plugin-types'?: Array<`${string}/${string}` | 'none'>;
/** @deprecated */ 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
type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
Loggerpermalink
interface Logger {
(msg: string): void;
success(msg: string): void;
error(msg: string): void;
warn(msg: string): void;
minor(msg: string): void;
info(msg: string): void;
}
MaybePromisepermalink
type MaybePromise<T> = T | Promise<T>;
PrerenderErrorHandlerpermalink
interface PrerenderErrorHandler {
(details: {
status: number;
path: string;
referrer: string | null;
referenceType: 'linked' | 'fetched';
}): void;
}
PrerenderOnErrorValuepermalink
type PrerenderOnErrorValue = 'fail' | 'continue' | PrerenderErrorHandler;
Prerenderedpermalink
interface Prerendered {
pages: Map<
string,
{
/** The location of the .html file relative to the output directory */ file: string;
}
>;
assets: Map<
string,
{
/** The MIME type of the asset */ type: string;
}
>;
redirects: Map<
string,
{
status: number;
location: string;
}
>;
/** An array of prerendered paths (without trailing slashes, regardless of the trailingSlash config) */ paths: string[];
}
RequestOptionspermalink
interface RequestOptions {
getClientAddress: () => string;
platform?: App.Platform;
}
ResponseHeaderspermalink
string[]
is only for set-cookie, everything else must be type of string
type ResponseHeaders = Record<string, string | number | string[] | null>;
RouteDefinitionpermalink
interface RouteDefinition {
id: string;
type: 'page' | 'endpoint';
pattern: RegExp;
segments: RouteSegment[];
methods: HttpMethod[];
}
RouteSegmentpermalink
interface RouteSegment {
content: string;
dynamic: boolean;
rest: boolean;
}
TrailingSlashpermalink
type TrailingSlash = 'never' | 'always' | 'ignore';
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:
/// <reference types="@sveltejs/kit" />
declare namespace App {
interface Locals {}
interface PageData {}
interface Platform {}
interface PrivateEnv {}
interface PublicEnv {}
}
By populating these interfaces, you will gain type safety when using env
, event.locals
and event.platform
.
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:
interface Locals {
user: import('$lib/types').User;
}
Or wrap the namespace with declare global
:
import { User } from '$lib/types';
declare global {
namespace App {
interface Locals {
user: User;
}
// ... }
}
Localspermalink
The interface that defines event.locals
, which can be accessed in hooks (handle
, and handleError
), server-only load
functions, and +server.js
files.
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
).
interface PageData {}
Platformpermalink
If your adapter provides platform-specific context via event.platform
, you can specify it here.
interface Platform {}
PrivateEnvpermalink
The interface that defines the dynamic environment variables exported from $env/dynamic/private
.
interface PrivateEnv extends Record<string, string> {}
PublicEnvpermalink
The interface that defines the dynamic environment variables exported from $env/dynamic/public
.
interface PublicEnv extends Record<string, string> {}
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
* foo: string;* bar: string;* baz: string* }>} */export async functionA 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.({ GET params }) {// ...}
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
import type * as Kit from '@sveltejs/kit';
interface 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 functionGET ({params }) {// ...}
src/routes/[foo]/[bar]/[baz]/+page.js
ts
/** @type {import('./$types').PageLoad} */export async functionload ({params ,fetch }) {// ...}
For this to work, your own
tsconfig.json
orjsconfig.json
should extend from the generated.svelte-kit/tsconfig.json
(where.svelte-kit
is youroutDir
):{ "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"
}
}