简体   繁体   中英

Vue 3 - Typescript - Object is possibly null issue

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.

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) 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM