'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>
Solution 1:[1]
This works for me
// This returns all the component's properties as a Partial: { prop1?: string, ... }
type ComponentProperties<T extends { $set: (...args: any) => any}> =
NonNullable<Parameters<T['$set']>[0]>;
// This returns the type of a specific property
type ComponentPropertyType<
T extends { $set: (...args: any) => any},
P extends keyof ComponentProperties<T>
> = NonNullable<ComponentProperties<T>[P]>;
Usage:
export let animalSpecies: ComponentPropertyType<Animal, 'species'> = ...;
Solution 2:[2]
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;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | bztes |
Solution 2 | m93a |