user3091275 user3091275 - 4 months ago 213
TypeScript Question

Typescript error TS1005: ':' expected. with Object.assign()

I have nested

Object.assign()
in typescript:

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


This yields those errors:

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.


The weird thing is that the errors vanish if I fix the key e.g.:

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


This left me clueless, why isn't it ok to call
action.item_id
at that place when he doesn't complain few characters after?

Answer

When using a variable as a property name in an object declaration, you need to use computed property notation by putting it in brackets:

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