简体   繁体   中英

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 eg:

(<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?

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
    })
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM