$ ./guess_the_languageProblem Solving — fix the bug
Problem Solving — fix the bug · medium · #254

Which fix removes the bug?

type User = { name?: string };
function nameLen(user?: User) {
  return user?.name.length;
}
nameLen({}); // TypeError
  1. Write user?.name?.length
  2. Write user!.name.length
  3. Use user?.['name'].length
  4. Declare name: string | null
?. only guards the value directly before it. user exists but name is undefined, so .length still throws; each optional link needs its own ?.
Play Problem Solving ▸