Skip to content

Commit 78131b9

Browse files
authored
[feat] TS interfaces for typing actions (#7121)
Fixes #6538
1 parent f24614c commit 78131b9

File tree

3 files changed

+46
-0
lines changed

3 files changed

+46
-0
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ node_modules
99
/compiler.*js
1010
/index.*js
1111
/ssr.*js
12+
/action
1213
/internal
1314
/store
1415
/easing

package.json

+3
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,9 @@
3939
"import": "./compiler.mjs",
4040
"require": "./compiler.js"
4141
},
42+
"./action": {
43+
"types": "./types/runtime/action/index.d.ts"
44+
},
4245
"./animate": {
4346
"types": "./types/runtime/animate/index.d.ts",
4447
"import": "./animate/index.mjs",

src/runtime/action/index.ts

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/**
2+
* Actions can return an object containing the two properties defined in this interface. Both are optional.
3+
* - update: An action can have a parameter. This method will be called whenever that parameter changes,
4+
* immediately after Svelte has applied updates to the markup.
5+
* - destroy: Method that is called after the element is unmounted
6+
*
7+
* Example usage:
8+
* ```ts
9+
* export function myAction(node: HTMLElement, paramater: Parameter): ActionReturn<Parameter> {
10+
* // ...
11+
* return {
12+
* update: (updatedParameter) => {...},
13+
* destroy: () => {...}
14+
* };
15+
* }
16+
* ```
17+
*
18+
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
19+
*/
20+
export interface ActionReturn<Parameter = any> {
21+
update?: (parameter: Parameter) => void;
22+
destroy?: () => void;
23+
}
24+
25+
/**
26+
* Actions are functions that are called when an element is created.
27+
* You can use this interface to type such actions.
28+
* The following example defines an action that only works on `<div>` elements
29+
* and optionally accepts a parameter which it has a default value for:
30+
* ```ts
31+
* export const myAction: Action<HTMLDivElement, { someProperty: boolean }> = (node, param = { someProperty: true }) => {
32+
* // ...
33+
* }
34+
* ```
35+
* You can return an object with methods `update` and `destroy` from the function.
36+
* See interface `ActionReturn` for more details.
37+
*
38+
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
39+
*/
40+
export interface Action<Element = HTMLElement, Parameter = any> {
41+
<Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter>;
42+
}

0 commit comments

Comments
 (0)