classnames icon indicating copy to clipboard operation
classnames copied to clipboard

Typescript: Throws an error when we pass spread operator of undefined

Open pajaydev opened this issue 3 years ago • 1 comments

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 ?.

pajaydev avatar Sep 07 '21 07:09 pajaydev

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

VitorLuizC avatar Nov 05 '21 22:11 VitorLuizC