Amala James
Amala James

Reputation: 1486

Spread opertor in Typescript throwing error

Below is the code snippet from my project where i use 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;
});

This code is throwing error in Play ground. Can some tell me why?

Upvotes: 1

Views: 74

Answers (2)

MartyIX
MartyIX

Reputation: 28648

There is an open issue for this: Support es7 Rest/Spread properties

It won't be implemented very soon I guess. See the comment:

We want to wait for the proposal to reach Stage 3 before addressing this.

and please see the specs status:

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

Upvotes: 1

Fenton
Fenton

Reputation: 250812

The spread operator is supported for function calls in TypeScript and is compiled to an apply call if you are targeting < ES6 - but you can't use it for creating an object yet:

Although this example returns the original object, with an updated property, I think it is what you were trying to achieve:

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

Or perhaps you wanted to create a new object, using destructuring:

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

Upvotes: 0

Related Questions