The optional chaining operator can be used to perform null checks before accessing a property, or calling a function.
Using &&
for this purpose is no longer required.
function getUsernameFromId(id: number): string | undefined {
const user = db.getUser(id)
return user && user.name
}
someFunc && someFunc()
// ^~~~ not necessary
maybeArray && maybeArray[index]
// ^~~~ not necessary
function getUsernameFromId(id: number): string | undefined {
const user = db.getUser(id)
return user?.name
}
someFunc?.()
maybeArray?.[index]