打字稿错误TS1005:':'预期。使用Object.assign()

时间:2016-08-02 12:39:12

标签: javascript typescript

我在typescript中嵌套了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是不是可以?

1 个答案:

答案 0 :(得分:4)

在对象声明中使用变量作为属性名称时,需要使用computed property表示法将其放在括号中:

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