在Typescript投掷错误中传播opertor

时间:2015-12-10 07:19:28

标签: typescript ecmascript-6

以下是我项目中使用Typescript的代码片段。

interface List {
    id: number;
    name: string;
    done: boolean;
};

let list = [{id: 0, name: "Vinoj", done: false},
        {id: 1, name: "Sandeep", done: true},
        {id: 2, name: "Amala", done: true},
        {id: 3, name: "Dixy", done: true},
        {id: 4, name: "Ajay", done: true},
        {id: 5, name: "Ashwin", done: true},
        {id: 6, name: "Yashin", done: true},
        {id: 7, name: "Mudassir", done: true},
        {id: 8, name: "Ishan", done: true}];

let listItemId = 2;

let updatedList:List[] = list.map(item => {
    if (item.id === listItemId)
        return {...item, done : !item.done};
    return item;
});

此代码在Play地面抛出错误。有人可以告诉我为什么吗?

2 个答案:

答案 0 :(得分:1)

对于TypeScript中的函数调用,支持扩展运算符,如果您要定位< {},则会将其编译为apply调用。 ES6 - 但你不能用它来创建一个对象:

虽然这个例子返回原始对象,并且有更新的属性,但我认为这是你想要实现的目标:

interface List {
    id: number;
    name: string;
    done: boolean;
};

let list = [
    {id: 0, name: "Vinoj", done: false},
    {id: 1, name: "Sandeep", done: true},
    {id: 2, name: "Amala", done: true},
    {id: 3, name: "Dixy", done: true},
    {id: 4, name: "Ajay", done: true},
    {id: 5, name: "Ashwin", done: true},
    {id: 6, name: "Yashin", done: true},
    {id: 7, name: "Mudassir", done: true},
    {id: 8, name: "Ishan", done: true}
];

let listItemId = 2;

let updatedList:List[] = list.map(item => {
    if (item.id === listItemId) {
        item.done = !item.done
    }
    return item;
});

或者您可能想要使用解构创建一个新对象:

        if (item.id === listItemId) {
            let { id, name, done } = item;
            return {
                id: id, name: name, done: !done
            }
        }
        return item;

答案 1 :(得分:1)

这是一个未解决的问题:Support es7 Rest/Spread properties

我猜它不会很快实现。请参阅comment

  

我们希望在解决此问题之前等待提案达到第3阶段。

请参阅规格状态:

https://github.com/sebmarkbage/ecmascript-rest-spread