Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 566
WoJ Avatar asked Aug 25 '26 06:08

WoJ


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>
like image 116
Boussadjra Brahim Avatar answered Aug 26 '26 21:08

Boussadjra Brahim


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
like image 24
codingwith3dv Avatar answered Aug 26 '26 20:08

codingwith3dv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!