展开运算符和解构

问题描述 投票:0回答:1
interface Item {
    id: string;
    title: string,
}

interface ItemState {
    entities: { [id: string]: Item };
}


const toBeDeleted = { id: '2', title: 'item_2' };

const state: ItemState = {
    entities: {
        '1': { id: '1', title: 'item_1' },
        '2': { id: '2', title: 'item_2' },
        '3': { id: '3', title: 'item_3' }
    }
};

const { [toBeDeleted.id]: deleted, ...remaingEntities } = state; // doesn't work

const newState = { entities: remaingEntities };

// That's what I'm trying to achive with the line, that doesn't work:

// deleted.toBe( { id: '2', title: 'item_2' } )

// newState.toBe( {
//     entities: {
//        '1': { id: '1', title: 'item_1' },
//        '3': { id: '3', title: 'item_3' }
//    }
// })

我想使用扩展运算符和解构删除一个项目,并将“状态”解构为两部分:

  1. 我要删除的项目
  2. 剩下的项目

基本上从状态中拉出'state.entities['2']'并保留其余部分。

这有可能吗,还是我在这里混合了两个概念?

typescript destructuring spread-syntax
1个回答
0
投票

要使用对象结构化和扩展运算符取出一个属性,您先命名您想要的属性,后跟一个逗号,然后使用扩展运算符。
例如:

const {propertyToRemove, ...oldObject} = newObject;

你的情况应该是:

const { '2', ...remaingEntities } = state;

© www.soinside.com 2019 - 2024. All rights reserved.