mgrubinger / blog

https://www.grooovinger.com/
MIT License
0 stars 0 forks source link

Export JSDoc Type from Svelte Components #40

Open mgrubinger opened 7 months ago

mgrubinger commented 7 months ago

short: How to export/import JSDoc @typedef definitions in Svelte

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>