[英]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.