【问题标题】:Is there a way to get the type of a component in vuejs?有没有办法在 vuejs 中获取组件的类型?
【发布时间】:2020-02-17 16:40:19
【问题描述】:

我正在使用 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;

如果没有虚拟功能,是否可以将其进一步降低?

编辑2:

InstanceType&lt;...&gt; 可以。

这行得通:

const MyComponent =  Vue.extend({
    data() {
        return {
            test: "test"
        }
    }
});

export type MyComponentInstance = InstanceType<typeof MyComponent>

let test : MyComponentInstance;
let str = test.test;

【问题讨论】:

  • 显然根据这个:typescriptlang.org/docs/handbook/functions.html#this-parameters你可以为这种类型的东西使用接口。
  • 技术上正确,但我不想在类型信息存在时在组件旁边维护接口定义。
  • 那么我是否正确地说您想要获取您提供给 Vue.extend() 函数的数据参数的返回类型?如果是这样,您已经拥有该功能。我发现了这个 SO:stackoverflow.com/questions/36015691/… 这表明您可以将该函数传递给 ReturnType&lt;type passed to that function&gt;,然后将其用作 myFunction 中的类型?
  • 我设法得到了一些工作。但我希望它更小。我仍然需要一个虚拟函数,它返回组件的一个实例。你已经很有帮助了:)
  • 进一步查看提到的拉取请求,我发现InstanceType。当像type MyCompomentInstance = InstanceType&lt;MyCompoment&gt; 这样使用时,这正是我所需要的。 @BillNaylor 非常感谢您为我指明正确的方向。

标签: typescript vue.js


【解决方案1】:

在@BillNaylor 的帮助下,我找到了正确的方向。

我需要使用InstanceType&lt;...&gt;

例子:

const MyComponent =  Vue.extend({
    data() {
        return {
            test: "test"
        }
    }
});

export type MyComponentInstance = InstanceType<typeof MyComponent>

let test : MyComponentInstance;
let str = test.test;

【讨论】:

  • 非常好的答案,先生。从那时起,我对类似问题有了一个通用的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-23
  • 2021-01-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多