2017-02-14 99 views
0

當我編譯下面的代碼(因爲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對象)的函數。

錯誤

(Period[]) =>

在一審中沒有錯誤

(Period) =>

+1

你總是有最佳的類型標註前一個強制性的名字。因此,Period是該位置的參數名稱,[]在該位置無效...... – Lucero

回答

1

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