In a function of the form
function myFunc(param: any) {}
How to properly check if param
can be spread? (...param
)
How to know if an unknown variable can safely be spread for any type of spread (array/object)?
In a function of the form
function myFunc(param: any) {}
How to properly check if param
can be spread? (...param
)
How to know if an unknown variable can safely be spread for any type of spread (array/object)?
You can check if it's iterable using the Symbol.iterator
property. If the variable is iterable, you can safely spread it.
Demo:
let arr = [1, 2, 3];
console.log(typeof arr[Symbol.iterator]); //function
let obj = { a: 1, b: 2, c: 3 };
console.log(typeof obj[Symbol.iterator]); //undefined
let unknownVar = [1, 2, 3];
if (unknownVar[Symbol.iterator]) {
let newArr = [...unknownVar];
console.log(newArr); //[1, 2, 3]
}