Typescript compiler does not notice "wrong" interface implementation

Viewed 20

Start with a union type StringOrStuff combining two unrelated types:

class Stuff {
  constructor(readonly n: number) {}
}
type StringOrStuff = string | Stuff;

Now define an interface with a function to accept this type as a parameter.

interface Convert {
  convert(x: StringOrStuff): string;
}

Finally declare a class which, I would say 'wrongly', implements the interface:

class Converter implements Convert {
  // How can this function signature
  // be an implementation of interface Convert?
  convert(stuff: Stuff): string {
    return 'n=' + stuff.n;
  }
}

The interface proclaims that implementing methods can work with either string or Stuff, yet this implementation isn't really prepared to deal with a string. See typscript playground for a full example.

Question: Can someone explain what is going on here? Is this is a bug or a Javascript or backwards compatibility feature? Is there a rationale anywhere in the docs? Can I "fix" this by defining the interface differently?

0 Answers
Related