How to use spread as parameters in function?
Asked Answered
D

3

7

I have tried this case:

let a = { id: 1, name: "Misha" };


function b(id: number, name: string) {

}

b(...a);

I need that all properties of object will be applied as parameters

Dizen answered 4/10, 2019 at 11:35 Comment(0)
D
9

TypeScript doesn't support spreading objects to parameter names.

If it's possible for you to change the function signature though, you can expect an object of a compatible type as the first function parameter, like this:

// interface name is just an example
interface IUser {
  id: number;
  name: string;
}

let a: IUser = { id: 1, name: "Misha" };

function b({ id, name }: IUser) {
  console.log(`User ID is ${id} and name is "${name}"`);
}

b(a);
Daph answered 4/10, 2019 at 11:38 Comment(2)
In this case why we use ...a instead a?Dizen
Straight no answer is very useful too. It stops the search and saves time. Thank you.Exerciser
P
0

like this.

function NewFunction(...[foo, bar]: Parameters<typeof OtherFunction>){}
function OtherFunction(enabled?: boolean; message?: string) {}
Perice answered 21/8, 2023 at 3:44 Comment(0)
N
-3

TypeScript does support spreading objects to parameter names.

Write the three dots before the parameter name, and an array operator next to the type.

Example :

function add(x: number, ...vals: number[])
Northrup answered 2/2, 2021 at 16:44 Comment(1)
This is for arrays only, not objects with named properties (or object literals)Daph

© 2022 - 2024 — McMap. All rights reserved.