TS2779
error TS2779: The left-hand side of an assignment expression may not be an optional property access.
Broken Code ❌
1 2 3 4 5 6
| type User = { id: number; name: string; } const someUsers: Map<string, User> = new Map(); someUsers.get('some-user-id')?.name = 'Benny';
|
Fixed Code ✔️
You cannot assign a value to a property which might be undefined
. As Map.get() may return undefined
, you have to add an existence check:
1 2 3 4 5 6 7 8 9
| type User = { id: number; name: string; } const someUsers: Map<string, User> = new Map(); const user = someUsers.get('some-user-id'); if (user) { user.name = 'Benny'; }
|