简体   繁体   中英

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

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

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

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