I have been struggling to find clear documentation or explanation for the unique relationship between a TypeScript class and an interface that share the same name.
- What is the significance of having an interface with the same name as a class?
- Why does a class automatically implement an interface with the same name?
- Why does the compiler raise errors when implementing readonly fields in a class and interface with matching names, but not when the names are different?
- Is there any official documentation that addresses these specific questions?
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;
}