Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript get Svelte component's prop type

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>
like image 561
Pete Avatar asked Jan 22 '26 01:01

Pete


2 Answers

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>
like image 87
agneuhold Avatar answered Jan 25 '26 16:01

agneuhold


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;
like image 34
m93a Avatar answered Jan 25 '26 16:01

m93a



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!