Which fix removes the bug?
type User = { name?: string };
function nameLen(user?: User) {
return user?.name.length;
}
nameLen({}); // TypeError
- Write
user?.name?.length - Write
user!.name.length - Use
user?.['name'].length - 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 ▸