I am trying to write this piece of code where a boolean value is extracted from an array of objects with a default value if the property does not exists
const flagArrayToBooleanArray_INITIAL_ERROR = (
arr: Array<{ value: string } | { value: string; flag: true }> = [{
value: "",
}, { value: "", flag: true }],
) => {
const flags: Array<boolean> = arr.map((obj) => obj.flag ?? false);
return flags;
};
}
Typescript complains on the function ({ flag }) => flag?? false
({ flag }) => flag?? false
as property flag
does not exist on type Empty | { flag: true }
Empty | { flag: true }
This can be fixed by converting te object to a map
function flagArrayToBooleanArrayFixedMap(
arr: Array<{ value: string } | { value: string; flag: true }> = [{ value: "" }, { value: "", flag: true }],
) {
return arr.map((obj) => {
const tmp = new Map(Object.entries(obj));
return tmp.get("flag") === true ? true : false;
});
}
Is there a way to tell typescript I know this might not exist, I want the default js behaviour in this case
?
Edit: Fixed some copy-paste errors, in the initial code there was no compiler error.
If you have items that may or may not have flags, having that typed correctly higher up would make this easier.
You can also define a type that may or may not have a flag property. Any object can "meet" that criteria (but may be undefined
).
type MayHaveFlag = { flag?: boolean };
function flagArrayToBooleanArray(
arr: MayHaveFlag[]
) {
const flags = arr.map(({ flag }) => !!flag);
return flags;
}
const values = [{}, {}, { flag: true }, { dont: 'care', what: 'this', has: 1 }];
const result = flagArrayToBooleanArray(values);
console.log(result);
So here, when we .map
over the objects, we get true
, false
, or undefined
as any of those could be values from any object. We can then use !!
to force into a true
or false
( undefined
becomes false
, other values stay the same) or you could keep flag?? false
flag?? false
if you prefer, as that would do the same thing.
You can note that my values
array does not even need a type declared, as the function parameter really has no requirements of the object other than that if it has a flag
property, it is boolean
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.