Skip to content

Commit bddd795

Browse files
authored
[feat] enhance action typings (#7805)
Allows a way to tell language tools which additional attributes and events the action brings to the HTML element Related sveltejs/language-tools#1553
1 parent 0ed453d commit bddd795

File tree

1 file changed

+19
-5
lines changed

1 file changed

+19
-5
lines changed

src/runtime/action/index.ts

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,17 @@
44
* immediately after Svelte has applied updates to the markup.
55
* - destroy: Method that is called after the element is unmounted
66
*
7+
* Additionally, you can specify which additional attributes and events the action enables on the applied element.
8+
* This applies to TypeScript typings only and has no effect at runtime.
9+
*
710
* Example usage:
811
* ```ts
9-
* export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter> {
12+
* interface Attributes {
13+
* newprop?: string;
14+
* 'on:event': (e: CustomEvent<boolean>) => void;
15+
* }
16+
*
17+
* export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {
1018
* // ...
1119
* return {
1220
* update: (updatedParameter) => {...},
@@ -17,9 +25,15 @@
1725
*
1826
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
1927
*/
20-
export interface ActionReturn<Parameter = any> {
28+
export interface ActionReturn<Parameter = any, Attributes extends Record<string, any> = Record<never, any>> {
2129
update?: (parameter: Parameter) => void;
2230
destroy?: () => void;
31+
/**
32+
* ### DO NOT USE THIS
33+
* This exists solely for type-checking and has no effect at runtime.
34+
* Set this through the `Attributes` generic instead.
35+
*/
36+
$$_attributes?: Attributes;
2337
}
2438

2539
/**
@@ -32,11 +46,11 @@ export interface ActionReturn<Parameter = any> {
3246
* // ...
3347
* }
3448
* ```
35-
* You can return an object with methods `update` and `destroy` from the function.
49+
* You can return an object with methods `update` and `destroy` from the function and type which additional attributes and events it has.
3650
* See interface `ActionReturn` for more details.
3751
*
3852
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
3953
*/
40-
export interface Action<Element = HTMLElement, Parameter = any> {
41-
<Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter>;
54+
export interface Action<Element = HTMLElement, Parameter = any, Attributes extends Record<string, any> = Record<never, any>> {
55+
<Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter, Attributes>;
4256
}

0 commit comments

Comments
 (0)