You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
We can annotate a payload for the emitted event. Also, all non-declared emitted events will throw a type error when called:
304
304
@@ -372,6 +372,77 @@ year.value = 2020 // ok!
372
372
If the type of the generic is unknown, it's recommended to cast `ref` to `Ref<T>`.
373
373
:::
374
374
375
+
### Typing Template Refs
376
+
377
+
Sometimes you might need to annotate a template ref for a child component in order to call its public method. For example, we have a `MyModal` child component with a method that opens the modal:
378
+
379
+
```ts
380
+
import { defineComponent, ref } from'vue'
381
+
382
+
const MyModal =defineComponent({
383
+
setup() {
384
+
const isContentShown =ref(false)
385
+
const open = () => (isContentShown.value=true)
386
+
387
+
return {
388
+
isContentShown,
389
+
open
390
+
}
391
+
}
392
+
})
393
+
```
394
+
395
+
We want to call this method via a template ref from the parent component:
396
+
397
+
```ts
398
+
import { defineComponent, ref } from'vue'
399
+
400
+
const MyModal =defineComponent({
401
+
setup() {
402
+
const isContentShown =ref(false)
403
+
const open = () => (isContentShown.value=true)
404
+
405
+
return {
406
+
isContentShown,
407
+
open
408
+
}
409
+
}
410
+
})
411
+
412
+
const app =defineComponent({
413
+
components: {
414
+
MyModal
415
+
},
416
+
template: `
417
+
<button @click="openModal">Open from parent</button>
418
+
<my-modal ref="modal" />
419
+
`,
420
+
setup() {
421
+
const modal =ref()
422
+
const openModal = () => {
423
+
modal.value.open()
424
+
}
425
+
426
+
return { modal, openModal }
427
+
}
428
+
})
429
+
```
430
+
431
+
While this will work, there is no type information about `MyModal` and its available methods. To fix this, you should use `InstanceType` when creating a ref:
432
+
433
+
```ts
434
+
setup() {
435
+
const modal =ref<InstanceType<typeofMyModal>>()
436
+
const openModal = () => {
437
+
modal.value?.open()
438
+
}
439
+
440
+
return { modal, openModal }
441
+
}
442
+
```
443
+
444
+
Please note that you would also need to use [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) or any other way to check that `modal.value` is not undefined.
445
+
375
446
### Typing `reactive`
376
447
377
448
When typing a `reactive` property, we can use interfaces:
0 commit comments