TypeScript 获取 Svelte 组件的 prop 类型

Pet*_*ete 12 typescript svelte

假设您正在使用从其他地方导入的组件

<Animal species={animalSpecies} /> // species has a specific type
Run Code Online (Sandbox Code Playgroud)

并且你想向它传递一个你期望从其他地方得到的某个变量:

<script lang="ts">
import Animal from 'animals'
export let animalSpecies : ???
</script>

<Animal species={animalSpecies} />
Run Code Online (Sandbox Code Playgroud)

一种方法是进入源文件并找到直接导入类型的方法。但是是否可以直接从组件中检索类型?

例如,如果有一种方法可以获取类似以下的 typeof:

export let animalSpecies : ComponentType<Animal.species>
Run Code Online (Sandbox Code Playgroud)

小智 17

使用现在可用的内置 Svelte 类型也可以实现这一点:

<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>
Run Code Online (Sandbox Code Playgroud)


m93*_*93a 6

安东尼的回答对我不起作用 \xe2\x80\x93 它将所有道具转换为可选。
\n然而,我能够使用以下内容:

\n
import type { SvelteComponentTyped } from "svelte";\nexport type Props<T> = T extends SvelteComponentTyped<infer P, any, any> ? P : never;\n\n// and a bonus:\nexport type Events<T> = T extends SvelteComponentTyped<any, infer E, any> ? E : never;\nexport type Slots<T> = T extends SvelteComponentTyped<any, any, infer S> ? S : never;\n
Run Code Online (Sandbox Code Playgroud)\n


小智 4

这对我有用

// 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]>;
Run Code Online (Sandbox Code Playgroud)

用法:

export let animalSpecies: ComponentPropertyType<Animal, 'species'> = ...;
Run Code Online (Sandbox Code Playgroud)