Consider the following example:
interface Vehicle{
mass:number
}
interface InspectorClass{
inspect(v:Vehicle):void
}
class Car implements Vehicle{
mass = 2000
wheels = 4
}
class Boat implements Vehicle{
mass = 3000
sails = 2
}
// with methods it silently fails:
class BoatInspector implements InspectorClass{
inspect(v:Boat){ // interface contract silently violated!!!
console.log(v.mass)
console.log(v.sails)
}
}
function runInspection(inspector:InspectorClass, vehicle:Vehicle){
inspector.inspect(vehicle)
}
let myCar = new Car()
let myBoatInspector = new BoatInspector()
runInspection(myBoatInspector, myCar)
// with functions it checks properly:
type InspectorFunction = (v:Vehicle) => void
const inspectCar:InspectorFunction = function(v:Car){ // TypeScript complains as it should
console.log(v.mass)
console.log(v.wheels)
}
Experience TypeScript in action here
The specification of the interface declares that an Inspect method in an InspectorClass instance must be capable of inspecting any type of Vehicle. Why does TypeScript allow me to implement a class that only accepts Boats without raising an error? Is this behavior intentional or is there a way to enable strict checking for this scenario?