Home > database >  Vue 3 - Typescript - Object is possibly null issue
Vue 3 - Typescript - Object is possibly null issue

Time:10-13

I checked other threads but couldn't find the solution.

setup() {
  const processingData = ref(null)
}

Function:

function create() {
  let field = JSON.parse(processingData.value.fields)

  for (let i = 0; i < field.length; i  ) {
    console.log(i)
  }
}

Error on JSON.parse(processingData.value.fields): Object is possibly 'null'.Vetur(2531) const processingData: Ref<null>

processingData is 100% accessable, as It's being set with another function already.

CodePudding user response:

In Typescript there is a Non-null assertion operator you can add to let your code know that the value won't be null when your using it:

let field = JSON.parse(processingData.value!.fields)

This should help. But as I see your processingData has no type. This will lead to another problem. TS can't find the property fields. So either parse it as any or add the type to your ref.

ref type:

setup() {
  const processingData: Ref<{ fields: any }> = ref({fields: null})
}
...
let field = JSON.parse(processingData.value!.fields)

or parse it as any like:

let field = JSON.parse((processingData.value as any).fields)

Otherwise you can logically make sure that the value is not null.

if(processingData.value){
  field = JSON.parse(processingData.value.fields) 
}
  • Related