【问题标题】:How to write a function that returns an array of objects using a custom interface type in Typescript如何使用 Typescript 中的自定义接口类型编写返回对象数组的函数
【发布时间】:2021-10-19 18:02:23
【问题描述】:

我正在尝试创建一个在使用接口类型时将对象推送到数组的函数。

这是我目前所拥有的,但我收到了Type 'number' is not assignable to type 'Customer' 的错误

这些是我已采取的步骤,我需要遵循:

  1. 声明一个“客户”类型的数组变量

  2. 该函数必须接受一个“客户”类型的对象。

  3. 函数返回类型必须是“客户”数组。

  4. 在函数内部,将传递给函数的对象添加到数组中。

  5. 函数必须返回数组。

// 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


    【解决方案1】:

    看看Array.prototype.push类型签名:

    Array<T>.push(...items: T[]): number
    

    在你的情况下:

    Array<Customer>.push(...items: Customer[]): number
    

    也看看docs

    push 需要 Customer 参数,无论您是否传递 person.name。这是不正确的。

    你应该传递Customer对象:

    function addCustomer(person: Customer) {
      // 3. Add the object to the customer array
      return customer.push(person)
    }
    

    此外,push 返回数组的新长度而不是传递的元素。表示push返回number是否要从addCustomer返回Customer

    【讨论】:

      【解决方案2】:

      您的代码不符合您的第三个要求:

      函数返回类型必须是“客户”数组。

      据此,您的函数应该返回一个数组。但是,您的函数签名说它返回一个 Customer 而不是 Customer[]。您的函数应改为如下类型:

      function addCustomer(person: Customer): Customer[] {
        return customer.push(person);
      }
      

      错误现在变为Type 'number' is not assignable to type 'Customer[]'。您正在返回Array.push 的结果,根据文档返回“调用该方法的对象的新长度属性”,它是一个数字,而不是数组。为了使其符合您的规范,它应该返回数组:

      function addCustomer(person: Customer): Customer[] {
        customer.push(person);
        return customer; // I would advise renaming this to the plural `customers` instead
      }
      

      之后,函数匹配预期的行为。

      请注意,TypeScript 的全部好处是可以在编译时或什至在您键入时捕获这些类型的错误。使用现代代码编辑器,您可以将鼠标悬停在 push 方法上,以查看它期望和返回的数据类型(在这种情况下是 number,而不是您期望的 Customer[])。

      【讨论】:

        猜你喜欢
        • 2021-07-31
        • 2020-11-02
        • 1970-01-01
        • 2019-01-15
        • 1970-01-01
        • 1970-01-01
        • 2018-11-11
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多