TypeScript如何直接获取已导入Svelte组件的prop属性类型
组件Prop类型提取方案
可以直接从导入的组件中提取对应prop的类型,不需要单独从组件源文件导入类型,不同技术栈的实现方式如下:
React 项目
使用React内置的ComponentProps工具类型实现:
<script lang="ts"> import type { ComponentProps } from 'react' import Animal from 'animals' // 提取单个species属性的类型 export let animalSpecies : ComponentProps<typeof Animal>['species'] </script> <Animal species={animalSpecies} />
如果需要复用整个组件的Props类型,也可以提前定义:
type AnimalComponentProps = ComponentProps<typeof Animal> export let animalSpecies : AnimalComponentProps['species']
Vue 3 + TS 项目
有两种常用实现方式:
- 基于组件实例类型提取:
import Animal from 'animals' type AnimalComponentProps = InstanceType<typeof Animal>['$props'] export let animalSpecies : AnimalComponentProps['species']
- 基于
ExtractPropTypes工具类型提取(适用于用defineProps声明属性的组件):
import type { ExtractPropTypes } from 'vue' import Animal from 'animals' type AnimalComponentProps = ExtractPropTypes<typeof Animal.props> export let animalSpecies : AnimalComponentProps['species']
Svelte 项目
Svelte 3.30及以上版本内置了ComponentProps工具类型,直接使用即可:
<script lang="ts"> import type { ComponentProps } from 'svelte' import Animal from 'animals' export let animalSpecies : ComponentProps<typeof Animal>['species'] </script> <Animal species={animalSpecies} />
注意:所有场景下都需要先通过
typeof Animal拿到组件的类型定义,再从中提取属性类型,不能直接使用Animal.species作为类型,因为Animal是运行时的组件值,无法直接用于类型声明场景。
内容的提问来源于stack exchange,提问作者Pete
相关产品推荐
相关产品推荐

