Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte - Extend standard html elements with typescript

I would like to define my custom component and specify which kind of "standard component" I would to extend.

This to consume VSCode intellisense for all standard attributes of the extended component without re-define all attributes.

This is what I would to do:

<script lang="ts">
    // Error: Cannot redeclare block-scoped variable '$$props'
    export let $$props: svelte.JSX.HTMLAttributes<HTMLButtonElement>;

    // OR

    // Error: Cannot redeclare block-scoped variable '$$restProps'
    export let $$restProps: svelte.JSX.HTMLAttributes<HTMLButtonElement>;

    export let myCustomProp: string;
</script>

<button {...$$restProps}>{myCustomProp}<slot /></button>

To explain better what I would like to do, I post the same case in React with Typescript:

import React from 'react';

type Props = {
  myCustomProp: string;
} & React.ButtonHTMLAttributes<HTMLButtonElement>;
export default function ({ myCustomProp, ...rest }: Props) {
  return (
    <button {...rest}>
      {myCustomProp}
      {rest.children}
    </button>
  );
}
like image 698
Emanuele Pavanello Avatar asked Mar 09 '26 22:03

Emanuele Pavanello


1 Answers

Use the svelte/elements to provide an interface $$Props that extends the specific HTML element you want to type.

Button.svelte:

<script lang="ts">
    import type { HTMLButtonAttributes } from 'svelte/elements'

    interface $$Props extends HTMLButtonAttributes {
      myCustomProp: string
    }

    export let myCustomProp: string
</script>

<button {...$$restProps}>
  {myCustomProp}
  <slot />
</button>

+page.svelte:

<script lang="ts">
  import Button from './Button.svelte'

  let disabled = false
</script>

<Button myCustomProp='foo' {disabled}>Click Me</Button>

EDIT: If you are dealing with more complex types you could us the typing you defined in $$Props in your exported props:

export let myCustomProp: $$Props["myCustomProp"]
like image 75
Dana Woodman Avatar answered Mar 12 '26 12:03

Dana Woodman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!