Pregunta

interface ClockInterface {
    setTime(d: Date);
}

class Clock implements ClockInterface  {
    // I would expect this to raise a compile error 
    // as it's not implementing the interface
    setTime(d) {
        // some logic that needs an instance of Date
    }
}

var cc = new Clock();

// otherwise it allows you to do any bad stuff you want.
cc.setTime(234);
cc.setTime('234');
cc.setTime([]);

Of course changing the setTime(d) { to setTime(d: Date) { then does cause warnings to be raised for the last 3 invocations of setTime.

A simpler examples is just:

class Clock implements ClockInterface  {
    setTime() {
        // some logic that needs an instance of Date
    }
}
¿Fue útil?

Solución

Liskov Substitution Principle. The class is substitutable for the interface, so it does implement it.

The only check TypeScript performs when you say implements is "is the class assignable to the specified interface?". Consider this case:

interface CatVeterinarian {
    checkup(a: Cat): void;
}

interface HumanDoctor {
    checkup(a: Human): void;
}

class UniversalDoctor implements CatVeterinarian, HumanDoctor {
    checkup(a: Animal) {
        // ...
    }
}

Presuppose for a minute that this was an error: How would you fix it? Your UniversalDoctor class really can act as both CatVeterinarian and HumanDoctor. There's nothing left for you to do.

The fact that you can invoke Clock with non-Date arguments simply represents an extra piece of functionality -- the ability to accept arbitrary setTime arguments. Obviously it would be absurd for the compiler to say "Your class does too much, it does not satisfy that interface*; nearly every implementor of an interface will have some extra 'stuff' that's not part of the original interface.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top