Subscribe on changes!

Let v-slot support both destructuring and type annotations

avatar
Nov 24th 2022

What problem does this feature solve?

I'm using Vite, Vue, Typescript, and Pug.

So far, v-slot has supported either destructuring or type annotations.

An example for destructuring:

SimpleGrid(:items="items" ...)
  template(v-slot="{item}")
    span(v-if="isS(item)") {{item}}
    span(v-else :class="item.cls") {{item.text}}

notes:

  • items is an array. It is types as string | Item.
    • Item is an interface: {text: string; cls: string | string[]}
  • isS is a method which uses lodash's isSting().

Here, v-slot="{item}" make the progrom create an variable item but its type is any.

I cannot enjoy linter functions like auto-completion, warning if I misspell "text" for "test", and so on.

An example for type annotations:

SimpleGrid(:items="items" ...)
    template(v-slot="__: {item: string | Item}")
        span(v-if="isS(__.item)") {{__.item}}
        span(v-else :class="__.item.cls") {{__.item.text}}

__.item is correctly recognized.

It works. But it is annoying to write __. everywhere.

What does the proposed API look like?

Just one step forward: combining both!

SimpleGrid(:items="items" ...)
  template(v-slot="{item}: {item: string | Item}")
    span(v-if="isS(item)") {{item}}
    span(v-else :class="item.cls") {{item.text}}

VS Code linter shows no error for {item}: {item: string | Item}, but vite server throws "SyntaxError: Unexpected token ':'"