[英]How to specify a Typescript function parameter array type
当我编译以下代码时(由于const
的类型和函数()
的类型不同,在我看来这是不正确的),不会产生任何错误:
export const yearsExtractor: (Period) => Year[] = (periods: Period[]): Year[] => periods && periods.length ? periods.map((period: Period) => period.year) : <Year[]>[];
当我编译以下代码(对我来说这是正确的,因为const
的类型与function ()
的类型匹配)时,将产生错误:
export const yearsExtractor: (Period[]) => Year[] = (periods: Period[]): Year[] => periods && periods.length ? periods.map((period: Period) => period.year) : <Year[]>[];
不同之处在于,未编译的代码将const
声明为一个接受Period
对象数组(而不是单个Period
对象)的函数。
错误
(Period[]) =>
没错
(Period) =>
第一个例子:
(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[]>[];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.