typescript - 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>
解决方案
做你想做的事情(输入你的代码)的更好方法是创建一个单独的文件夹types
(例如)并创建其中包含接口的文件。例如components.interface.ts
. 在那里你定义了你所有的接口(或类型,但接口工作得更快,但做同样的事情)。
// types/components.interface.ts
export interface Foo {
bar: () => void;
}
这将有助于使您的组件代码保持整洁有序。
推荐阅读
- c++ - Qt - 带有注释的 JSON
- javascript - 如何检查php中的空序列化字符串?
- unity3d - 应用高速跟随一个目标时忽略 Unity 2D 碰撞
- node.js - req.session.captcha 不在 Node.js 中的不同端口上工作
- xamarin - Xamarin 不同的部署方法(即席、发布、调试等)
- assembly - 程序计数器保存当前地址还是下一条指令的地址?
- reactjs - 循环中的更新状态不起作用
- spring - 无法连接到运行 Junit 测试的 Redis
- arrays - 在另一个数组 SWIFT 4 中循环遍历数组和分组连续数字的最佳方法?
- r - 安装失败:似乎不是 R 包(没有说明