🩹

Svelte5で`Complex binding patterns require an ...`エラーが発生した時の応急対処

2024/12/30に公開

一旦JSDocを使いましょう

何が起きたか

svelte-sanitizeをSvelte5にアップデートしていたところ以下のようなコードでエラーが発生。

<script lang="ts">
  import { sanitize } from '@jill64/universal-sanitizer'

  let {
    html,
    options = undefined
  }: {
    html: string
    options?: Parameters<typeof sanitize>[1]
  } = $props()

  let sanitized = $derived(sanitize(html, options))
</script>

{@html sanitized}
x Build failed in 694ms
error during build:
[vite-plugin-svelte] [plugin vite-plugin-svelte] dist/Render.svelte (7:3): dist/Render.svelte:7:3 Complex binding patterns require an initialization value
https://svelte.dev/e/js_parse_error
file: /Users/jill/Git/svelte-sanitize/dist/Render.svelte:7:3

  5 |      html,
  6 |      options = undefined
  7 |    }: {
          ^
  8 |      html: string
  9 |      options?: Parameters<typeof sanitize>[1]


 ELIFECYCLE  Command failed with exit code 1.

応急対処

他の同様のコードでは発生しなかったので一旦JSDocで型補完を効かせた。

<script>
  import { sanitize } from '@jill64/universal-sanitizer'

  /**
   * @typedef {Object} Props
   * @property {string} html
   * @property {Parameters<typeof sanitize>[1]} [options]
   */

  /** @type {Props} */
  let { html, options = undefined } = $props()

  let sanitized = $derived(sanitize(html, options))
</script>

{@html sanitized}

考えられる原因

Viteでのビルド時にTSの型情報が残ってしまっていると推測。
正しい対処方法はわからないのでご存知の方がいれば、コメント欄にてご教授ください。

Discussion