打字稿错误TS1005:“:”。与Object.assign()

use*_*275 4 javascript typescript

我嵌套Object.assign()在打字稿中:

(<any>Object).assign({}, state, {
    action.item_id: (<any>Object).assign({}, state[action.item_id], {
        label_value: action.value
    })
})
Run Code Online (Sandbox Code Playgroud)

这将产生这些错误:

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.
Run Code Online (Sandbox Code Playgroud)

奇怪的是,如果我修复密钥,错误将消失,例如:

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

这让我一无所知,action.item_id当他之后不抱怨几个字符时,为什么不能在那个地方打电话呢?

Joh*_*yHK 5

在对象声明中将变量用作属性名称时,需要通过在方括号中使用计算的属性表示法:

(<any>Object).assign({}, state, {
    [action.item_id]: (<any>Object).assign({}, state[action.item_id], {
        label_value: action.value
    })
})
Run Code Online (Sandbox Code Playgroud)