ivanhofer / sveltekit-typescript-showcase

This repository shows how Svelte and SvelteKit work together with TypeScript.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question: get reference with type to current component

ptrxyz opened this issue · comments

commented

Hello Ivan, your repo is super helpful, it covers so many cases I was running into quite regularly.
I am missing one thing, maybe you can help:

I wanted to create a component that emits an event with a reference to the emitting component instance.

const dispatch = createEventDispatcher<{
  myEvent: { data: string, ref: ReturnType<typeof get_current_component> } 
}>();

dispatch("myEvent", { data: "some string", ref: get_current_component() })

This doesn't work since get_current_component() is untyped and simply any. The obvious workaround would be to bind:this in the parent component but this can get messy if you only need the reference once and maybe inside the event handler.

TL;DR: i was wondering if you know a better way how to get the reference to the current instance and its type from within the component itself.

Something like this?

image

<script lang="ts">
	import type Component from './Component.svelte';
	import { createEventDispatcher } from 'svelte'

	const dispatch = createEventDispatcher<{
		myEvent: { data: string, ref: Component }
	}>()

	export let prop: number
</script>

{prop}
<script lang="ts">
	import type { ComponentEvents } from 'svelte'
	import Component from './Component.svelte'

	const handleEvent = ({ detail }: ComponentEvents<Component>['myEvent']) => {
		detail.ref.$set({ prop: '' })
	}
</script>

<Component prop={7} on:myEvent={handleEvent} />
commented

Wow, nice, it wasn't clear to me that I can simply import the type from the current file.
But you didn't only answer my question, ComponentEvents also was new to me. I was always using $$events_def but ComponentEvents seems much cleaner.

Thank you a bunch!

Yeah I have created the PR for ComponentEvents in the Svelte repo, but forgot to update the example here when it got merged ^^