Typings for $refs should also include Component | Component[]
See original GitHub issueVersion
2.6.10
Reproduction link
https://codesandbox.io/s/p7krpry9vm
Steps to reproduce
- Assign a component a
ref
attribute, say,<my-component ref="myComponent" />
- Import the typings for component from vue, i.e.
import { Component as VueComponent } from 'vue';
(the aliasing is needed because I am also usingvue-property-decorator
’sComponent
module, but that is not relevant to the question) - Declare the types for
$refs
when composing a component, i.e.public readonly $refs!: { myComponent: VueComponent }
What is expected?
I expect the Component
type to be accepted in the $refs
definition.
What is actually happening?
I get a message that the type of this.$refs.myComponent
is incompatible with the pre-existing type declared for this.$refs.<key>
.
Here is a screenshot of the actual error I am getting in production code:
This issue came across because I need to access a nested element within a Vue component when writing in TypeScript. In native JS, I can simply query the DOM of the Vue component using this.$refs.myComponent.$el.querySelector(...)
without an issue. However, in TypeScript, I get a warning because I need to pre-declare the typings for $refs
at the top of the component, i.e.:
public readonly $refs!: {
myComponent: VueComponent
}
When you log this.$refs.myComponent
when the parent/consuming component is mounted to the console, you will see that it returns a Vue component instance. This is incompatible with the pre-existing typings for $refs
, which only allows the following types: Vue | Element | Vue[] | Element[]
.
I propose that the typings for $refs
by extended to:
{ [key: string]: Vue | Element | Component | Vue[] | Element[] | Component[] }
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
I believe
$refs
contains either dom element(s) or component instance(s).Component
in Vue’s typing is actually the component configuration object or component class, not the component instance itself.You typing should be
$refs: { myComponent: Vue}
IMHO@terrymun
@Component({ name: 'MyComponent' })
export default class MyComponent extends Vue { }
MyComponent is extendsVue
, so can use$refs!: { myComponent: Vue }
with generic type.