Les types RequestHandler et Load acceptent tous les deux un argument Params vous permettant de
typer l’objet params. Par exemple, ce endpoint attend les paramètres foo, bar et baz :
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
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.
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.
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
})=>{ // ...
};
Bien sûr, cela est fastidieux à écrire, et moins portable (si vous devez renommer le dossier [foo]
en [qux], le type ne reflèterait plus la réalité).
Pour résoudre ce problème, SvelteKit génère des fichiers .d.ts pour chacun de vos endpoints et
pages :
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.
Ces fichiers peuvent être importés dans vos endpoints et pages en tant que fichiers se trouvant dans
le même dossier, grâce à l’option rootDirs de
votre configuration TypeScript :
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
The parameters of the current route - e.g. for a route like /blog/[slug], a { slug: string } object.
Inside query functions (including query.batch and query.live), accessing this property throws an error.
Pass values from the page as arguments to the query instead. Inside form and command functions it relates to the page
the remote function was called from, not the URL of the endpoint SvelteKit creates for the remote function. Never use it
to determine whether or not a user is authorized to access certain data, as these values are part of the request which could be manipulated.
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 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
})=>{ // ...
};
Les types de retour des fonctions load sont alors rendus disponibles via le module $types en
tant que PageData et LayoutData respectivement, tandis que l’union des valeurs de retour de
toutes les Actions est rendu disponible en tant que ActionData.
À partir de la version 2.16.0, deux types utilitaires additionnels sont fournis : PageProps
définit data: PageData ainsi que form: ActionData (lorsque des actions sont définies), tandis
que LayoutProps définit data: LayoutData ainsi que children: Snippet.
Pour que cela fonctionne, votre fichier tsconfig.json ou jsconfig.json devrait hériter
de la configuration générée $app/types :
{ "extends": "$app/tsconfig" }
app.d.ts
Le fichier app.d.ts est l’endroit où sont définis les types d’ambience de votre application, c-à-d
les types qui sont disponibles sans avoir besoin de les importer explicitement.
Le namespace App fait toujours partie de ce fichier. Ce namespace contient différents types qui
influencent la forme de certaines fonctionnalités de SvelteKit avec lesquelles vous interagissez.
Il est possible de dire à SvelteKit comment typer les objets au sein de votre application en
déclarant le namespace App. Par défaut, un nouveau projet aura un fichier appelé src/app.d.ts et
contenant ce qui suit :
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:
The export {} line exists because without it, the file would be treated as an ambient module which prevents you from adding import declarations.
If you need to add ambient declare module declarations, do so in a separate file like src/ambient.d.ts.
By populating these interfaces, you will gain type safety when using event.locals, event.platform, and data from load functions.
La ligne export {} existe car sinon, le fichier serait considéré comme un module ambiant, ce qui
empêcherait d’y ajouter des déclarations d’import.
Si vous avez besoin d’ajouter des déclaration ambiantes declare module, faites-le dans un fichier
distinct comme par exemple src/ambient.d.ts.
En remplissant ces interfaces, vous obtiendrez du typage lorsque vous utiliserez event.locals,
event.platform, et les data venant des fonctions load.
Error
Définit la forme commune des erreurs prévues et imprévues. Les erreurs prévues sont jetées en
utilisant la fonction error. Chaque erreur passe à travers le hook handleError, qui doit
retourner cette forme (avec status et message optionnels, puisque par défaut ces propriétés sont
celles de l’erreur attrapée).
interfaceError{…}
status:number;
message:string;
Locals
L’interface qui définit event.locals, qui est accessible dans les hooks serveur
(handle, et handleError), les fonctions load de serveur, et les fichiers +server.js.
interfaceLocals{}
PageData
Définit la forme commune des états page.data c’est-à-dire les données
partagées entre toutes les pages.
Les fonctions Load et ServerLoad dans les dossiers ./$types seront restreintes en fonction.
Utilisez des propriétés optionnelles pour les données qui ne sont présentes que sur certaines pages.
N’ajoutez pas de signature d’indice ([key: string]: any).
interfacePageData{}
PageState
La forme de l’objet page.state, qui peut être manipulé en utilisant la fonction
goto.