Vue3 Typescript Refs

Posted on  by admin

In this Vue tutorial we learn how to work with refs with TypeScript. We cover how to explicit type a ref and work with complex types, interfaces and interface arrays.

How to explicit type a ref. This lesson is a continuation of the previous.

It requires an app generated by the Vue CLI with TypeScript enabled.

Becauserefreturns a reference object and not the actual value, we can’t use type assertion on refs.

Instead, we have to use a generic argument. To do that, we specify the type(s) inside a pair of open-and-close<>(angle brackets) before the parentheses.

As an example, let’s define two refs. One will be typed explicitly, the other will use type inference. When we run the example in the browser, everything works as expected.

If we’re using an object in a ref, the object’s properties can use type assertion.

When we run the example in the browser, everything works as expected.