Export JSDoc Type from Svelte Components

2024-02-09 / mgrubinger / 0 reactions

The component which defines the type needs to do so in a <script context="module"> block (see Svelte docs on context=“module”)

// ReusableComponent.svelte
<script context="module">
/**
 * An option object for <Select>
 * @typedef {Object} SelectOption
 * @property {string} value the value of this option
 * @property {string} label the visible label to render
 */
</script>

// ... rest of the component

then, in the importing component you can refer to the type by importing it from the module:

// MyComponent.svelte

<script>
import ReusableComponent from './ReusableComponent.svelte`

/** @type {import('./ReusableComponent.svelte').SelectOption[]} */
let optionsList = [
  {label: 'Option 1', value: 1},
  {label: 'Option 2', value: 2},
]
</script>
Leave a reaction if you liked this post! 🧡
Leave a new comment