2016-08-02 37 views
4

我在打字稿嵌套Object.assign()Typescript錯誤TS1005:':'預計。與Object.assign()

(<any>Object).assign({}, state, { 
    action.item_id: (<any>Object).assign({}, state[action.item_id], { 
     label_value: action.value 
    }) 
}) 

這將產生這些錯誤:

ERROR in ./src/reducers/ItemsReducer.ts 
(2,19): error TS1005: ':' expected. 

ERROR in ./src/reducers/ItemsReducer.ts 
(2,26): error TS1005: ',' expected. 

ERROR in ./src/reducers/ItemsReducer.ts 
(2,28): error TS1136: Property assignment expected. 

奇怪的是,如果我解決的關鍵例如錯誤消失:

(<any>Object).assign({}, state, { 
    "fixed_key": (<any>Object).assign({}, state[action.item_id], { 
     label_value: action.value 
    }) 
}) 

這讓我一無所知,爲什麼在這個地方打電話action.item_id時他不會抱怨幾個字符?

回答

4

當一個對象的聲明使用變量作爲屬性名稱,你需要把它放在括號內使用computed property符號:

(<any>Object).assign({}, state, { 
    [action.item_id]: (<any>Object).assign({}, state[action.item_id], { 
     label_value: action.value 
    }) 
}) 
+0

謝謝! :)它現在像一種魅力。 – user3091275