Is there any sugar to ensure that map will not typeerror using tools like optional chaining / nullishcoalescing ?
let x = {y: 1, z: 2};
x?.map(i => i); // Typeerror
Array.isArray(x)?.map(i => i); // Typeerror
let y = '1234';
y?.length && y.map(i => i) // Typeerror
These type errors seem to be correct. You obviously can't call map on an object literal, boolean, or string.
If you want to optionally call map anyways, you can continue the optional chaining with ?.(params)
:
let x = {y: 1, z: 2};
x?.map?.(i => i);
Array.isArray(x)?.map?.(i => i);
let y = '1234';
y?.length && y.map?.(i => i)
Keep in mind this only checks if a property called map
exists and is non-null/undefined. If it does exist but isn't a function, you'll still get an error.
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.