[英]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: 当我编译以下代码时(由于
const
的类型和函数()
的类型不同,在我看来这是不正确的),不会产生任何错误:
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: 当我编译以下代码(对我来说这是正确的,因为
const
的类型与function ()
的类型匹配)时,将产生错误:
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). 不同之处在于,未编译的代码将
const
声明为一个接受Period
对象数组(而不是单个Period
对象)的函数。
error 错误
(Period[]) =>
no error 没错
(Period) =>
in the first instance: 第一个例子:
(Period) => Year[]
reads as a function, with parameter Period:any
, the second instance: 读取为带有参数
Period:any
的函数,第二个实例:
(Period[]) => Year[]...
is invalid syntax because you've not given a name to the function variable (you need to). 是无效的语法,因为您没有给函数变量命名(需要)。
try (period: 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.