Search code examples
typescriptclassinterfacelanguage-lawyer

What does it mean by "can be treated as the interface type" in TypeScript handbook?


In the handbook, it says that:

It’s important to understand that an implements clause is only a check that the class can be treated as the interface type. It doesn’t change the type of the class or its methods at all. A common source of error is to assume that an implements clause will change the class type - it doesn’t!

But I don't understand what it means by "can be treated as the interface type" when it also says "It doesn’t change the type of the class or its methods at all."

Does it mean that I need to repeat the exact same types for both the class and the interface?

They give an example where the type of s is any:

interface Checkable {
  check(name: string): boolean;
}
 
class NameChecker implements Checkable {
  check(s) {
    // Notice no error here
    return s.toLowerCase() === "ok";
  }
}

Solution

  • Clause 1: Can be treated as an interface type:

    Suppose you create an interface and two different classes implement it like the below:

    interface Alphabet {
      x: number;
      y?: number;
    }
    class C implements Alphabet { //Error
      z = 0; 
    }
    class D implements Alphabet { 
      x= 1; 
      y = 0;
    }
    

    c gives an error because c can not be treated as something of type Alphabet. implements keyword is there to make that check and gives an error.

    Playground

    Clause 2: Doesn’t change the type of the class or its methods at all:

    In the below example, one might (erroneously) expect c.y to be valid, albeit undefined. But that is not the case. Because The type of c is still C, it is not Alphabet.

    interface Alphabet {
      x: number;
      y?: number;
    }
    class C implements Alphabet {
      x = 0;
    }
    class D implements Alphabet {
      x= 1;
      y = 0;
    }
    const c = new C();
    const d = new D();
    
    c.y; //Error
    d.y; //No Error
    

    Playground

    And that is the confusion, the handbook warns against.