简体   繁体   中英

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) =>

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[]>[];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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