【问题标题】:Why is TS complaining of type usage when a type entry is expected?当需要输入类型时,为什么 TS 会抱怨类型使用?
【发布时间】:2021-10-28 00:43:43
【问题描述】:

考虑以下 Vue3 组件的代码,它接收对象数组作为道具:

<script lang="ts">

interface CorveesI {
  What: string,
  Who: string,
  Debit: number
}

export default {
  name: 'Corvees',
  props: {
    corvees: {
      type: CorveesI[]
    }
  },
(...)

在编译的时候,我在type: CorveesI[]这一行有一个警告:

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

我真的不知道该怎么办,因为 我正在告诉 corvees 是什么类型,给一个类型,我被告知它是一个类型,但需要一个值。

我阅读了Type Checks 上的文档,但我没有看到interface 和构造函数之间的桥梁。

由于我认为我对interface 的理解可能不正确,所以我阅读了TS doc for Object Types,但它很像类型描述(例如类似于Golang 中的type)。所以我迷路了。

【问题讨论】:

标签: typescript vue.js types typeerror vuejs3


【解决方案1】:

试试这个:

import { PropType } from "vue";
...
corvees: {
  type: Array as PropType<CorveesI[]>
}

参考:https://v3.vuejs.org/guide/typescript-support.html#annotating-props

【讨论】:

    【解决方案2】:

    prop definitions 中预期的 type 不是 TypeScript 类型(因为当 TS 编译器将您的代码转换为纯 JS 时,所有 TS 类型都会被编译掉),而是 JS 运行时类型。所以只有上面链接文档中提到的类型是有效的。

    要在 TS 中正确键入 prop,必须使用 PropType&lt;&gt; - Annotating props

    import { PropType } from "vue";
    ...
    corvees: {
      type: Array as PropType<CorveesI[]>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多