Home > Blockchain >  Typescript error when using array.map in a function
Typescript error when using array.map in a function

Time:06-10

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; 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?

I'm trying to create a function that takes an array of Object1 and converts to array of Object2

CodePudding user response:

This:

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

means that you are saying transformArray is of type 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 Object1s and returns an array of Object2s. 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.

Playground

  • Related