-
-
Notifications
You must be signed in to change notification settings - Fork 2.2k
Types for enhance function callback #7161
Description
Describe the problem
I would like to have the result object parameter of enhance function to be typed.
Example:
+page.server.ts
import { invalid, type Actions } from '@sveltejs/kit';
export const actions: Actions = {
default: async (event) => {
// get data from form
const data = await event.request.formData();
const name = data.get('name');
const surname = data.get('surname');
// validation
const errors = validate({name, surname});
if (errors) {
return invalid(400, {
name,
surname,
errors
});
}
// call external be or db
const result = await fetch('<url>', { body: JSON.stringify({name, surname}) });
if (!result.ok) {
return invalid(500, {
name,
surname,
beError: await result.text()
})
}
return {
name,
surname,
result: await result.json()
}
}
};
+page.svelte
<script lang="ts">
import { applyAction, enhance } from '$app/forms';
import type { ActionData } from './$types';
export let form: ActionData;
</script>
<form
method="POST"
use:enhance={(event) => {
return async ({ result }) => {
if (result.type === 'success') {
alert('hello ' + result.data?.name);
}
applyAction(result);
};
}}
>
<input type="text" name="name" placeholder="Name" value={form?.name || ''} />
<input type="text" name="surname" placeholder="Surname" value={form?.surname || ''} />
<button type="submit" class="btn btn-primary ">Salva</button>
</form>
So in +page.svelte i have the correct types on form object so that in input value <input type="text" name="name" placeholder="Name" value={form?.name || ''} /> the editor suggest me that form object has a name property.

Insted in enhance callback the result.data is a Record<string, any> | undefined and I don't know what kind of data the +page.server.ts sent.

Describe the proposed solution
I'm trying to find a solution but for now the only workaround that is working for me is to not use enhance but instead use a custom listener like the docs says (https://kit.svelte.dev/docs/form-actions#progressive-enhancement-custom-event-listener) but I'm afraid that without the use of the enhance function I lose the ability to make the form work in the absence of javascript.
Alternatives considered
No response
Importance
would make my life easier
Additional Information
No response