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



我正试图在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);
}

如果您不介意在创建Car Interface:之后使用Typescript接口

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

编辑:

作为@Chin。乌达拉提议。

如果您发现验证器没有得到类型推断或成员完成不起作用,用预期类型注释参数可能会有所帮助解决这些问题。

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

查看Vue.js的Typescript支持文档,了解有关注释道具的更多信息。

相关内容

最新更新