WoJ
WoJ

Reputation: 30054

How to use ref with typescript?

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?

Upvotes: 6

Views: 11667

Answers (2)

Boussadjra Brahim
Boussadjra Brahim

Reputation: 1

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>

Upvotes: 19

codingwith3dv
codingwith3dv

Reputation: 369

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

Upvotes: 3

Related Questions