【问题标题】:How can I exported a type from a Vue 3 single file Typescript component?如何从 Vue 3 单文件 Typescript 组件中导出类型?
【发布时间】:2021-08-19 04:13:11
【问题描述】:

我在一个文件组件中定义了一个类型,我想在另一个组件中使用它。但是,当我在那里导入该类型时,Typescript 声称该类型未导出,ESLint 将其视为any。因此像@typescript-eslint/no-unsafe-assignment 这样的规则会被触发。我发现的一种解决方法是创建一个与组件具有相同基本文件名的 .d.ts 定义文件,但我希望我的组件保留一个文件。

最小(非)工作示例:

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>

导入组件.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>

【问题讨论】:

  • 我无法在新搭建的 Vue CLI TypeScript 项目中重现它。你能分享一个复制的链接吗?
  • 有趣的注释:以上似乎适用于最新版本的 Vue CLI 等。但那是因为您要在 .vue 文件 into another .vue 文件中导入一个类型。如果您尝试从.vue 文件导入.ts 文件,它仍然无法正常工作。

标签: typescript vue.js eslint vuejs3


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2021-02-01
    • 2017-06-19
    • 2020-01-18
    • 2021-01-03
    • 2021-01-11
    • 2021-11-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多