Neoheurist
Neoheurist

Reputation: 3484

How to specify a Typescript function parameter array type

When I compile the following code (which to me seems incorrect because the type of the const and the type of the function () are different) no errors are produced:

export const yearsExtractor: (Period) => Year[] = (periods: Period[]): Year[] => periods && periods.length ? periods.map((period: Period) => period.year) : <Year[]>[];

When I compile the following code (which to me seems correct because the type of the const and the type of the function () match) an error is produced:

export const yearsExtractor: (Period[]) => Year[] = (periods: Period[]): Year[] => periods && periods.length ? periods.map((period: Period) => period.year) : <Year[]>[];

The difference being that the code that is not compiling is declaring the const as a function that accepts an array of Period objects (as opposed to a single Period object).

error

(Period[]) =>

no error

(Period) =>

Upvotes: 1

Views: 4715

Answers (1)

Meirion Hughes
Meirion Hughes

Reputation: 26448

in the first instance:

(Period) => Year[] 

reads as a function, with parameter Period:any, the second instance:

(Period[]) => Year[]... 

is invalid syntax because you've not given a name to the function variable (you need to).

try (period: Period[]) => Year[]...

export const yearsExtractor: (period: Period[]) => Year[] = (periods: Period[]): Year[] => periods && periods.length ? periods.map((period: Period) => period.year) : <Year[]>[];

Upvotes: 3

Related Questions