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

Viewed 3822

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>
2 Answers

Better way of doing what you want to do (type your code) is to create a separate folder types (for example) and create file with interfaces in it. For example components.interface.ts. And there you define all your interfaces (or types, but interfaces work faster but do the same).

// types/components.interface.ts
export interface Foo {
  bar: () => void;
}

That would help to keep your the code of your components cleaner and organized.

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>
Related