Home > Mobile >  Fixing typescript error in the return type of my function
Fixing typescript error in the return type of my function

Time:09-02

I have this function that returns an array of strings or undefined, typescript correctly infers the return type :

enter image description here

However if I explicit state that return type in the function I get an error: enter image description here

How can I fix this?

CodePudding user response:

Check more about adding type for arrow function here

it should be:

export const getBannerImgsId = (componentSlot: ContentSlot): string[]|undefined => {
 // your codes
}

or

export const getBannerImgsId = (componentSlot: ContentSlot): (componentSlot: ContentSlot) => string[]|undefined => {
 // your codes
}

or for the way I'm doing. ( I think it would be better for teamwork )

type BannerFunction = (componentSlot: ContentSlot) => string[]|undefined;

export const getBannerImgsId = (componentSlot: ContentSlot): BannerFunction  => {
 // your codes
}

CodePudding user response:

Typing the return value of an arrow function should be done after the parentheses, like this:

    const myFunction = (numbers: number[] | undefined): number[] | undefined => {
  return numbers?.filter(num => num !== 1)
}

You can read more about Function Types in the official documentation.

  • Related