Currently facing an issue with TypeScript and types.
I have an array of IDs obtained from checkboxes, which may also be empty.
An example of values returned from the submit() function:
const responseFromSubmit = {
1: {
id: "1",
value: "true"
},
2: {
id: "2",
value: "false"
},
3: {
id: "3",
value: "false"
}
};
const Ids: number[] = Object.values(submit()!)
.map(formfield => {
if (formfield.value === 'true') {
return Number(formfield.id);
}
})
.filter(id => id != undefined);
In this scenario, the resulting Ids would be Ids = [1].
I attempted different solutions like modifying the value after the code block by checking if Ids is undefined:
if (ids.length > 0){
ids = []
}
As a result, the constant Ids is of type (Number | undefined)[], but I aim to always have it as type number[], even when empty.
Here is one potential solution, although not preferred:
const Ids: number[] = Object.values(submit()!)
.map(formfield => {
if (formfield.value === 'true') {
return Number(formfield.id);
} else {
return 0;
}
})
.filter(id => id != 0);
In my situation, formfield.id will never equal 0, so filtering out all elements with a value of 0 is feasible. However, I do not recommend this solution. But hey, it does work, right? ¯\_(ツ)_/¯