[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 https://github.com/sveltejs/language-tools/pull/1553
pull/7832/head
Simon H 2 years ago committed by GitHub
parent 0ed453dc11
commit bddd795746
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -4,9 +4,17 @@
* immediately after Svelte has applied updates to the markup. * immediately after Svelte has applied updates to the markup.
* - destroy: Method that is called after the element is unmounted * - destroy: Method that is called after the element is unmounted
* *
* Additionally, you can specify which additional attributes and events the action enables on the applied element.
* This applies to TypeScript typings only and has no effect at runtime.
*
* Example usage: * Example usage:
* ```ts * ```ts
* export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter> { * interface Attributes {
* newprop?: string;
* 'on:event': (e: CustomEvent<boolean>) => void;
* }
*
* export function myAction(node: HTMLElement, parameter: Parameter): ActionReturn<Parameter, Attributes> {
* // ... * // ...
* return { * return {
* update: (updatedParameter) => {...}, * update: (updatedParameter) => {...},
@ -17,9 +25,15 @@
* *
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action * Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
*/ */
export interface ActionReturn<Parameter = any> { export interface ActionReturn<Parameter = any, Attributes extends Record<string, any> = Record<never, any>> {
update?: (parameter: Parameter) => void; update?: (parameter: Parameter) => void;
destroy?: () => void; destroy?: () => void;
/**
* ### DO NOT USE THIS
* This exists solely for type-checking and has no effect at runtime.
* Set this through the `Attributes` generic instead.
*/
$$_attributes?: Attributes;
} }
/** /**
@ -32,11 +46,11 @@ export interface ActionReturn<Parameter = any> {
* // ... * // ...
* } * }
* ``` * ```
* You can return an object with methods `update` and `destroy` from the function. * You can return an object with methods `update` and `destroy` from the function and type which additional attributes and events it has.
* See interface `ActionReturn` for more details. * See interface `ActionReturn` for more details.
* *
* Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action * Docs: https://svelte.dev/docs#template-syntax-element-directives-use-action
*/ */
export interface Action<Element = HTMLElement, Parameter = any> { export interface Action<Element = HTMLElement, Parameter = any, Attributes extends Record<string, any> = Record<never, any>> {
<Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter>; <Node extends Element>(node: Node, parameter?: Parameter): void | ActionReturn<Parameter, Attributes>;
} }

Loading…
Cancel
Save