Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

TS error when building Svelte 5 component that renders either anchor or button element based on presence of href prop

$
0
0

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:

  1. When destructuring props: href does not exist on Props type.
  2. 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.


Viewing all articles
Browse latest Browse all 1541

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>