如何使用点差作为函数中的参数?

问题描述 投票:0回答:1

我已经尝试过这种情况:

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


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

}

b(...a);

我需要将对象的所有属性都应用为参数

typescript typescript2.0
1个回答
1
投票

TypeScript不支持将对象传播到参数名称。

但是如果可以更改函数签名,则可以将兼容类型的对象作为第一个函数参数,如下所示:

// 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);
© www.soinside.com 2019 - 2024. All rights reserved.