How to use ref with typescript?

Viewed 2421

I am trying to learn Vue3 + Typescript (I so far wrote Vue2 apps with plain JS). I am trying to define a reactive variable in setup() :

setup() {
    // a single note
    interface Note {
      id: string
      creationDate: string
      text: string
      tags: string[]
      deleted: boolean
    }
    // all the notes in the app
    let allNotes: ref(Note[])  // ← this is not correct
    let allnotes: Note[]  // ← this is correct but not reactive
    
    (...)
  }

What is the correct syntax for creating a reactive Array of Note?

2 Answers

It should be placed between <> :

let allNotes= ref<Note[]>([]) 

by default the ref infers the type from the initial value like

const name=ref('') //name is a type of string

Ref typing :

interface Ref<T> {
  value: T
}

function ref<T>(value: T): Ref<T>

No need of making a reactive object for that It is used for an object

Like @Boussadjra Brahim said add a type to the ref function like this

let reactiveNoteArray = ref<Note[]>([]); //Add this angle bracket when using custom types and interfaces
Related