为 Vue 道具创建类型的正确方法是什么

What is a proper way to create a type for Vue props

我正在尝试在 Vue js 中为我的道具创建一个自定义 type,我创建了一个类型文件夹并将其添加到 tsconfig.typeRoots IntelliSense 中,其他所有东西都有效正确地,在编译时没有问题但是当我访问该组件时,我得到一个错误 Car is not defined 但我已经定义了它并且它在其他地方工作但是在检查官方文档之后我知道 prop 期望一个 constructor 所以我将类型重新定义为 declare class Car 并添加了一个构造函数原型,但同样的问题。

文件如下: 汽车部件

<script lang="ts">
import Vue from "vue";

export default Vue.extend({
  name: "the-car",
  props: {
    car: {
      required: true,
      type: Car,
    },
  },
});
</script>

types/common/index.d.ts声明文件

declare class Car {
    name: String;
    image: String;
    kms: Number;
    gears: String;
    desc: String;
    fuel: String;
    engine: String;
    price: Number;
    constructor(name: String, image: String, kms: Number, gears: String, desc: String, fuel: String, engine: String, price: Number);
}

如果您介意使用 Typescript 接口,那么您可以查看此 post

在你的例子中,在创建 Car Interface 之后:

props: {
  car: {
    required: true,
    type: Object as () => Car,
  },
},

编辑:

作为@Chin。 Udara 提议。

If you find validator not getting type inference or member completion isn’t working, annotating the argument with the expected type may help address these problems.

import Vue, { PropType } from 'vue'

const Component = Vue.extend({
  props: {
    car: {
      required: true,
      type: Object as PropType<Car>,
    }
  }
})

查看来自 Vue.js 的 Typescript Support docs 了解更多信息。