我正在用typescript构建一个vuejs应用程序。我想最大限度地利用可用的类型。
大多数情况下,类型和类型推断都工作得很好。
在某些代码中,我希望传递对特定组件类型的引用。即
const MyComponent = Vue.extend({...});
function myFunction(someComponent: MyComponent) {
...
}不幸的是,这会导致错误:
'MyComponent' refers to a value, but is being used as a type here.
有效的方法是创建一个实例,然后在函数声明中使用该实例的typeof:
const MyComponent = Vue.extend({...});
let myComponentInstance = new MyComponent();
function myFunction(someComponent: typeof myComponentInstance ) {
...
someComponent.someProperty;
...
}有没有一种方法可以在不创建MyComponent实例的情况下做到这一点?对我来说,这应该是可能的,因为知识就在那里。
编辑:
在@Bill-Naylor的建议下,我得出了以下结论。
const MyComponent = Vue.extend({
data() {
return {
test: "test"
}
}
});
let dummy = () => new MyComponent();
export type MyComponentInstance = ReturnType<typeof dummy>
let test : MyComponentInstance;
let str = test.test;有没有可能在没有虚拟函数的情况下让它更低呢?
Edit2:
使用InstanceType<...>可以做到这一点。
这是可行的:
const MyComponent = Vue.extend({
data() {
return {
test: "test"
}
}
});
export type MyComponentInstance = InstanceType<typeof MyComponent>
let test : MyComponentInstance;
let str = test.test;发布于 2019-10-22 16:13:50
在@BillNaylor的帮助下,他给我指明了正确的方向,我能够找到一个解决方案。
我需要使用InstanceType<...>
示例:
const MyComponent = Vue.extend({
data() {
return {
test: "test"
}
}
});
export type MyComponentInstance = InstanceType<typeof MyComponent>
let test : MyComponentInstance;
let str = test.test;https://stackoverflow.com/questions/58488865
复制相似问题