首页 > 解决方案 > How can I exported a type from a Vue 3 single file Typescript 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>

标签: typescriptvue.jseslintvuejs3

解决方案


做你想做的事情(输入你的代码)的更好方法是创建一个单独的文件夹types(例如)并创建其中包含接口的文件。例如components.interface.ts. 在那里你定义了你所有的接口(或类型,但接口工作得更快,但做同样的事情)。

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

这将有助于使您的组件代码保持整洁有序。


推荐阅读