4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

概要

見たらわかるのでコードを書きます。

Element.svelte

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

	type OmitStringSignature<T> = {
		[K in keyof T as K extends string ? (string extends K ? never : K) : K]: T[K];
	};
	type As = keyof OmitStringSignature<SvelteHTMLElements>;

	let {
		as
	}: {
		as: As;
	} = $props();
</script>

<svelte:element this={as} />

使用する側

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

<Element as="a" />
<Element as="hoge" /> // error!

おわり。

svelte:elementthisは実はhogeとかを型上渡せちゃうので縛りたいな〜とずっと思っていましたが、ふと思い立ってCopilotに聞いたら全部教えてくれました。

もう俺いらんわ…

ちなみに
<svelte:element this={"hoge"}>
	{@render children()}
</svelte:element>

と書くと

<hoge>テキスト</hoge>

と表示されます。

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?