ES6 Setters |错误TS2300:重复的标识符

时间:2016-02-29 23:23:23

标签: angularjs typescript ecmascript-6 setter

我正在为Angular 2组件编写一个类,该组件使用输入/输出装饰器和类似的setter:

export class ItemDetails {

    // Assign our `item` to a locally scoped property
    @Input('item') _item: Item;
    originalName: string;
    selectedItem: Item;

    // Allow the user to save/delete an item or cancel the
    // operation. Flow events up from here.
    @Output() saved = new EventEmitter();
    @Output() cancelled = new EventEmitter();

    // Perform additional logic on every update via ES6 setter
    // Create a copy of `_item` and assign it to `this.selectedItem`
    // which we will use to bind our form to
    set _item(value: Item) {

        if (value) this.originalName = value.name;
          this.selectedItem = Object.assign({}, value);
    }
}

我非常确定,除非我错过了这段代码应该没问题的东西,但我收到了错误:

error TS2300: Duplicate identifier '_item'

非常感谢任何有关其原因的见解:)

2 个答案:

答案 0 :(得分:3)

为了完成我想要做的事情,这个修订后的课程工作正常:

export class ItemDetails {

    @Input('item') set _item(value: Item) {

        if (value) this.originalName = value.name;
          this.selectedItem = Object.assign({}, value);
    }
    originalName: string;
    selectedItem: Item;

    @Output() saved = new EventEmitter();
    @Output() cancelled = new EventEmitter();
}

答案 1 :(得分:1)

setter不会附加到现有属性上,它是自己的类成员 - 您无法定义_item,然后将setter命名为相同的东西。

相关问题