TypeScript Version: 2.2.1
I'm having a lot of trouble finding an explanation for the errors below:
Code
// Co-named interface and class doesn't like readonly property implementation:
interface Foo {
readonly x: number; // Error: Duplicate identifier 'x'
y: number;
}
class Foo {
get x(): number { // Error: Duplicate identifier 'x'
return 0;
}
y = 1;
}
// Same as above, but different class name + explicit `implements`
class Bar implements Foo {
get x(): number { // No error!
return 0;
}
y = 1;
}
// Duplicating the first example, but explicitly implementing the co-named interface:
interface Baz {
readonly x: number; // Error: Duplicate identifier 'x'
y: number;
}
class Baz implements Baz {
get x(): number { // Error: Duplicate identifier 'x'
return 0;
}
y = 1;
}
Why does TypeScript complain about duplicate identifiers between a readonly field in an interface that merges with a class that implements that field as a getter?
An interface and a class with the same name "merge".
more information can be found at: http://www.typescriptlang.org/docs/handbook/declaration-merging.html
@mhegazy
I have the same question with this. For property and it's getter, type checker should not consider them as different during merging, for readonly property can be implemented as getter.
Also, there's some other question: when readonly property being merged, the property can not be assigned in constructor.
interface Rect {
width: number;
height: number;
readonly area: number;
}
class Rect implements Rect {
readonly area: number;
constructor(public width: number,public height: number){
this.area = this.width * this.height; // Error: Cannot assign to 'area' because it is a constant or a read-only property.
}
}
Most helpful comment
An interface and a class with the same name "merge".
more information can be found at: http://www.typescriptlang.org/docs/handbook/declaration-merging.html