Is there a way to unpack an array as arguments for a function?
For example in python if I have:
user = ["John", "Doe"]
def full_name(first_name, last_name):
return first_name + last_name
Then full_name(*user) unpack my user array and pass each of its items as argument of full_name.
Is that possible to achieve such a behavior in JavaScript/TypeScript?
You want the ...spread operator.
const user = ["John", "Doe"] as const
function fullName(firstName: string, lastName: string): string {
return firstName + lastName
}
fullName(...user)
Note the as const.
In order for this to have type safety in Typescript, the array needs to be a two item tuple of type [string, string] and not just an array of unknown length like string[]. This is because in order to guarantee type safety there must be at least 2 strings in that array in order to satisfy both arguments. as const forces typescript to treat that array as a tuple with known strings and length instead.
Playground
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With