typescripttypescript2.0

How to use spread as parameters in function?


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


Solution

  • 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);