Home > Net >  How to get a nested and optional object value with a default value and define type?
How to get a nested and optional object value with a default value and define type?

Time:07-06

Should be a simple one... I just want to get data.user.roles, but data could be empty. In that case, I need an empty array as result. Also I need to define the type of user - which is in this case any. So this is, what I came up with:

const { data } = useSession()
const user: any = data?.user || {} // define user
const roles = user?.roles || []

It works, but it doesn't feel very smart.

And I am not quite sure, if this would work if useSession doesn't return full dataset:

type Session = {
  data: {
    user?: {
        roles?: string[]
    }
  }
}
const {
  data: {
    user: { roles = [] }
  }
}: Session = useSession()

CodePudding user response:

data is guaranteed to exist according to the Session type, so you don't need a ? after that. From there you just drill in and provide a fallback at the end.

const { data } = useSession()
const roles = data.user?.roles ?? []

See playground

  • Related