Let's say you are using a component that has been imported from elsewhere
<Animal species={animalSpecies} /> // species has a specific type
and you want to pass it a certain variable that you expect from somewhere else:
<script lang="ts">
import Animal from 'animals'
export let animalSpecies : ???
</script>
<Animal species={animalSpecies} />
One way to do this would be to go into the source file and find a way to import the type directly. But is it possible to retrieve the type directly from the component?
If there was a way, for example, to get the typeof like:
export let animalSpecies : ComponentType<Animal.species>
This is also possible using the built-in Svelte types that are available now:
<script lang="ts">
import type { ComponentProps } from 'svelte';
import Animal from 'animals';
// The below has the types of all props on the Animal component now
export type AnimalPropTypes = ComponentProps<Animal>;
</script>
Anthony's answer didn't work for me – it converted all the props to optional.
Hoewever, I was able to use the following:
import type { SvelteComponentTyped } from "svelte";
export type Props<T> = T extends SvelteComponentTyped<infer P, any, any> ? P : never;
// and a bonus:
export type Events<T> = T extends SvelteComponentTyped<any, infer E, any> ? E : never;
export type Slots<T> = T extends SvelteComponentTyped<any, any, infer S> ? S : never;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With