user14325
user14325

Reputation: 382

How can I export a type from a Vue 3 single file component?

I have a type defined in one single file component that I would like to use in another component. However when I import that type there, Typescript claims the type is not exported and ESLint treats it any. Thus rules like @typescript-eslint/no-unsafe-assignment are triggered. One workaround I found, is creating a .d.ts definition file of the same base file name as the component, but I would like my components to stay a single file.

Minimum (not) working example:

ExportingComponent.vue

<template>
  <div />
</template>

<script lang="ts">
import { defineComponent } from 'vue'

export type foo = { bar: () => void }

export default defineComponent({
  name: 'ExportingComponent'
})
</script>

<style></style>

ImportingComponent.vue

<template>
  <div />
</template>

<script lang="ts">
import { defineComponent } from 'vue'
import { foo } from './ExportingComponent'

export default defineComponent({
  name: 'ImportingComponent',

  setup () {
    // next line triggers @typescript-eslint/no-unsafe-assignment
    const fooFoo = {} as Partial<foo>

    /* do something with fooFoo... */
 
    return {}
  }
})
</script>

<style>
</style>

Upvotes: 14

Views: 17040

Answers (1)

dangermace
dangermace

Reputation: 133

Another way to handle this is using <script setup>, which allows you to also use a "normal" script tag in the same component.

<!-- ExportingComponent.vue -->
<template>
  <div />
</template>

<script lang="ts">
export type foo = { bar: () => void }
</script>

<script setup lang="ts">
import { ref } from 'vue'

const someVar = ref(1)
</script>

<style></style>

Upvotes: 13

Related Questions