I have a type
export type ItemResponse = {
....
addedManually: boolean;
....
}
At some point I parse a JSON response into this type like this:
const response = await fetch(
`https://api.com`
);
const json: ItemResponse = await response.json();
console.log(json?.manuallyAdded)
return json;
The console log gives me undefined
, because my API does not return any value for manuallyAdded
. This field is only needed for usage inside the client-Application. I expected manuallyAdded
to be false
by default, but it is undefined
. How can I get around this. I would like to avoid manually setting this filed to false
for each response. Would there be any easy JS/TS way to change the default value without adding another wrapper-type
?
Thanks in advance
CodePudding user response:
you can simply do this:
const json: ItemResponse = {manuallyAdded:false,...await response.json()};
if manuallyAdded comes from server it will be overrided
CodePudding user response:
response.json()
will only deserialize fields that actually exist in the response. If manuallyAdded
doesn't exist, it will be undefined. If you want it to be false you have to set it to false yourself. One way is like this:
const defaultItemResponse: ItemResponse = {
manuallyAdded: false,
// other default values if you need them
};
const json: ItemResponse = await response.json();
const item = { ...defaultItemResponse, ...json };
console.log(item?.manuallyAdded)
return item;
CodePudding user response:
Although, technically you can't set a default value for interface fields, it doesn't mean it's a hopeless situation. Let's consider a simple use-case:
interface SomeInterface {
x?: boolean,
y: string
}
const defValue = {
x: false,
y: "some default value"
}
const test = {
y:"hello"
}
console.log({
...defValue,
...test
})
This is just a dirty approach. If you use TS, you can benefit from types like Pick, Omit, Partial to make your code cleaner, I would also recommend to create a factory method like:
const create = (val: SomeInterface): SomeInterface => ({...defValue, ...val})
which you can use on demand wherever you need to fill in default values. If you used classes instead of interfaces, that'd make things a bit easier as you could set those up in a constructor, and actually ensure the fields.