简体   繁体   English

在函数中使用 array.map 时出现打字稿错误

[英]Typescript error when using array.map in a function

interface Object1{
    id:number,
    label:string
}

interface Object2{
    id:number,
    description:string
}


const transformArray:Object2[] = (input:Object1[])=>{
    return input.map(item=>{
        return {
            id:item.id,
            description:item.label
        }
    })
}

In this code typescript gives the error在此代码中,打字稿给出了错误

Type '(input: Object1[]) => { id: number;输入'(输入:Object1 [])=> { id:数字; description: string;描述:字符串; }[]' is missing the following properties from type 'Object2[]': pop, push, concat, join, and 28 more.ts(2740) index.tsx(44, 34): Did you mean to call this expression? }[]' 缺少类型 'Object2[]' 的以下属性:pop、push、concat、join 和 28 个更多。ts(2740) index.tsx(44, 34):您是要调用这个表达式吗?

I'm trying to create a function that takes an array of Object1 and converts to array of Object2我正在尝试创建一个函数,该函数采用 Object1 数组并转换为 Object2 数组

This:这个:

const transformArray:Object2[] = (input:Object1[])=>{

means that you are saying transformArray is of type Object2[] .意味着您说transformArray的类型是Object2[] And then you assigning a function to it.然后你给它分配一个功能。 An array and a function are not compatible types, so you get a type error.数组和函数不是兼容的类型,因此会出现类型错误。


I think you meant to do this:我认为您打算这样做:

const transformArray = (input:Object1[]): Object2[] => {

Here you declare a function that accepts an array of Object1 s and returns an array of Object2 s.在这里,您声明一个接受Object1数组并返回Object2数组的函数。 transformArray does not require an explicit type because the function your are assigning to it very strongly typed and Typescript can figure out the tight type from that. transformArray不需要显式类型,因为您分配给它的函数是非常强类型的,Typescript 可以从中找出紧密类型。

Playground 操场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM