如何指定Typescript函数参数数组类型

时间:2017-02-14 01:03:28

标签: typescript

当我编译以下代码时(由于const的类型和函数()的类型不同而对我来说似乎不正确)没有产生错误:

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

当我编译以下代码时(由于const的类型和函数()的类型匹配而对我来说似乎是正确的)会产生错误:

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

不同之处在于,未编译的代码将const声明为接受Period对象数组的函数(而不是单个Period对象)。 / p>

错误

(Period[]) =>

没有错误

(Period) =>

1 个答案:

答案 0 :(得分:2)

在第一个实例中:

(Period) => Year[] 

作为函数读取,带参数Period:any,第二个实例:

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

是无效的语法,因为您没有给函数变量命名(您需要)。

尝试(period: Period[]) => Year[]...

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