Conditionally add to array or object in Typescript

· Bj√∂rn-Eric's Developer notes

Avoid undefined params in objects by conditionally spreading them.
#typescript

Conditionally add to object

1const { name, id } = user;
2const conditionallyAdded = {
3	// Conditionally add name if it exists
4	...(name && { name }),
5	// ... and add id (if it exists) as userId
6	...(id && {userId: id}) 
7}

Conditionally add to array

1// Add 'canEdit' and 'canDelete' to userPrivileges array if user is admin
2const userPrivileges = ['canRead', 'canWrite']
3const privileges = [
4	...(user.isAdmin ? ['canEdit', 'canDelete'] : []),
5	...userPrivileges
6]

@ref MDN: Spread syntax (...)


Home