Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unpacking an array in a function call

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?

like image 732
Haezer Avatar asked Jul 19 '26 19:07

Haezer


1 Answers

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

like image 114
Alex Wayne Avatar answered Jul 21 '26 09:07

Alex Wayne