Relationship between a TypeScript class and an interface of the same name

I'm having trouble finding any clear documentation or explanation for the seemingly special relationship between the TypeScript class and an interface with the same name.

  • What does an interface with the same name as the class have?
  • Why does a class that has its own name with an interface implement this interface automatically?
  • Why does the compiler complain about my readter implementation of the getter interface field when the class and interface have the same name but accept the implementation if the names are different?
  • Is there canonical documentation to address these issues?

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;
}
+6
source share
1 answer

:

interface Foo {
    x: number;
}

interface Foo {
    y: string;
}

let g = {} as Foo;
g.x; // OK
g.y; // OK

, , , .

class Bar {
    y: number;
}

interface IBaz extends Bar { } // includes y: number

class CBaz implements Bar {
    y: number = 5;
}

, , , .

, Typescript :

export interface Foo {
    readonly x: number;
}

export class Foo {
    readonly x: number = 3;
}

get x() { return 3; }, readonly x: number, , , ( readonly getter).

+7

Source: https://habr.com/ru/post/1016090/


All Articles