I’m trying to create a Svelte 5 component that renders either a button or anchor element based on the presence of a href prop, however I’m running into a TS error.
Button.svelte
<script lang="ts">
import type { HTMLButtonAttributes, HTMLAnchorAttributes } from 'svelte/elements';
type Props = HTMLAnchorAttributes | HTMLButtonAttributes;
const {
href,
children,
...restProps
}: Props = $props();
</script>
{#if href}
<a {href} {...restProps}>
{@render children()}
</a>
{:else}
<button {...restProps}>
{@render children()}
</button>
{/if}
The above produces two errors:
- When destructuring props:
href
does not exist on Props type. - When spreading
restProps
: Argument of type … is not assignable to parameter of type ‘HTMLProps<“a”, HTMLAtributes>’
I thought checking for the existence of href
would act as a type guard allowing me to spread the correct props on the correct element.
Any insights appreciated. Thanks in advance.