From 859e5daac375978bcec963079b7c195a9efafd10 Mon Sep 17 00:00:00 2001 From: Ignatius Bagus Date: Sun, 27 Feb 2022 01:37:12 +0700 Subject: [PATCH] [feat] TS interfaces for typing actions (#7121) Fixes #6538 --- .gitignore | 1 + package.json | 3 +++ src/runtime/action/index.ts | 42 +++++++++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 src/runtime/action/index.ts diff --git a/.gitignore b/.gitignore index ee1daa2c032d..22389f683ce4 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ node_modules /compiler.*js /index.*js /ssr.*js +/action /internal /store /easing diff --git a/package.json b/package.json index 2ca79c5fa897..c58f999bd3b4 100644 --- a/package.json +++ b/package.json @@ -39,6 +39,9 @@ "import": "./compiler.mjs", "require": "./compiler.js" }, + "./action": { + "types": "./types/runtime/action/index.d.ts" + }, "./animate": { "types": "./types/runtime/animate/index.d.ts", "import": "./animate/index.mjs", diff --git a/src/runtime/action/index.ts b/src/runtime/action/index.ts new file mode 100644 index 000000000000..6d1d39413932 --- /dev/null +++ b/src/runtime/action/index.ts @@ -0,0 +1,42 @@ +/** + * Actions can return an object containing the two properties defined in this interface. Both are optional. + * - update: An action can have a parameter. This method will be called whenever that parameter changes, + * immediately after Svelte has applied updates to the markup. + * - destroy: Method that is called after the element is unmounted + * + * Example usage: + * ```ts + * export function myAction(node: HTMLElement, paramater: Parameter): ActionReturn { + * // ... + * return { + * update: (updatedParameter) => {...}, + * destroy: () => {...} + * }; + * } + * ``` + * + * Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action + */ +export interface ActionReturn { + update?: (parameter: Parameter) => void; + destroy?: () => void; +} + +/** + * Actions are functions that are called when an element is created. + * You can use this interface to type such actions. + * The following example defines an action that only works on `
` elements + * and optionally accepts a parameter which it has a default value for: + * ```ts + * export const myAction: Action = (node, param = { someProperty: true }) => { + * // ... + * } + * ``` + * You can return an object with methods `update` and `destroy` from the function. + * See interface `ActionReturn` for more details. + * + * Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action + */ +export interface Action { + (node: Node, parameter?: Parameter): void | ActionReturn; +}