classnames
classnames copied to clipboard
Typescript: Throws an error when we pass spread operator of undefined
Code snippet:
import classNames from "classnames";
const styles = undefined;
console.log(classNames(["ui-component", ...styles]))
Error:
Cannot read property 'length' of undefined
shall we add a type check to prevent this ?.
undefined
is not a iterable, you can't spread it like arrays, strings etc. A type check can't prevent it, because its a runtime error.
You can use nullish-coalescing to prevent like in the example below:
import classNames from "classnames";
const styles = undefined;
console.log(classNames(["ui-component", ...styles ?? []]))
// /\
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator