【发布时间】:2021-10-19 18:02:23
【问题描述】:
我正在尝试创建一个在使用接口类型时将对象推送到数组的函数。
这是我目前所拥有的,但我收到了Type 'number' is not assignable to type 'Customer' 的错误
这些是我已采取的步骤,我需要遵循:
-
声明一个“客户”类型的数组变量
-
该函数必须接受一个“客户”类型的对象。
-
函数返回类型必须是“客户”数组。
-
在函数内部,将传递给函数的对象添加到数组中。
-
函数必须返回数组。
// Create Customer interface
interface Customer {
name: string
id: number
}
// 1. Declare an array variable of type 'Customer'
let customer: Customer[] = []
// 2. Create a f(n) that accepts one objec of type 'Customer'
function addCustomer(person: Customer): Customer {
// 3. Add the object to the customer array
return customer.push(person.name, person.id)
}
const customer1 = {
name: 'molly',
id: 101,
}
console.log(addCustomer(customer1))
/*Sample Output:
[ { name: 'molly', id: 101 } ]
*/
【问题讨论】:
标签: typescript types interface