I have a function that will call an external resource (e.g. REST) and will return a JSON object depending on the result.
For instance if I send a POST and it works, I need the object to be:
{ 
    code: 201, 
    id: <new_id_added> 
}
But when it fails for some reason, I don't want the id (cause it will be undefined). Something like:
{ 
    code: 400
}
So to have one single handling I have this:
response = { 
    code: result.code,
    id: result.id 
}
Which would work when all is OK, but then when it fails it would render:
{ 
    code: 400, 
    id: undefined
}
Is there any way to make "id" be optional, depending on whether it is defined? Something like:
response = { 
    code: result.code,
    id?: result.id
}
Then on "undefined" it will just be left out? I know I can just take the object and run a filter later to remove undefined attributes, but I think this would be just overkill, given that most of the times the response will be successful
 
     
     
    