Vue + TypeScript prop类型错误: “‘Foo’只能用作类型引用,但在此处作为值使用。”

huangapple go评论64阅读模式
英文:

Vue + TypeScript prop type error: "'Foo' only refers to a type, but is being used as a value here."

问题

我相对较新于 TypeScript 和 Vue Composition API,我发现以下错误令我感到困惑:

我有一个组件,它以一个名为 api 的 prop 作为参数,这个参数应该是一个 AxiosInstance

export default defineComponent({
  props: {
    api: AxiosInstance,
(...)

但是,当我尝试将 prop 的类型设置为 AxiosInstance 时,我收到以下错误:

TS2693: 'AxiosInstance' 只引用了一个类型,但在此处被用作值。

这对我来说很令人困惑,因为我的印象是在这种类型的 prop 对象中将类型用作值。例如,我另一个 prop 的定义如下:

    fileExtensionFilter: {
      type: String,
      default: undefined
    },

我应该如何正确定义这个 api prop 的类型?

英文:

I'm relatively new to TypeScript and the Vue Composition API and I find the following error confusing:

I have a component which takes as a prop an api variable which should be an AxiosInstance:

export default defineComponent({
  props: {
    api: AxiosInstance,
(...)

But when I try to set the type of the prop to be AxiosInstance, I get the following error:

> TS2693: 'AxiosInstance' only refers to a type, but is being used as a
> value here.

This is confusing to me, because my impression is that I'm using types as the values in this kind of prop object. For example, I have another prop defined as follows:

    fileExtensionFilter: {
      type: String,
      default: undefined
    },

How do I properly define the type of this api prop?

答案1

得分: 5

我从一位同事那里得到了解决方案:

在使用defineComponent()时,你需要使用Vue的PropType助手,文档中有描述在这里

因此,代码应该如下所示:

import { PropType } from 'vue'
export default defineComponent({
  props: {
    api: Object as PropType<AxiosInstance>,
    (...)
英文:

I got the solution from a coworker:

When using defineComponent(), you need to use Vue's PropType helper, described in the docs here.

So the code should look like this:

import {PropType} from &#39;vue&#39;
export default defineComponent({
  props: {
    api: Object as PropType&lt;AxiosInstance&gt;,
(...)

huangapple
  • 本文由 发表于 2023年1月9日 03:01:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75050517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定