为什么 TypeScript 允许在方法参数中隐式向下转换?
Why does TypeScript allow implicit downcast in method parameters?
示例如下:
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)
}
接口的契约声明 InspectorClass 实例中的检查方法必须能够检查任何类型的 Vehicle。为什么 TypeScript 让我实现一个实际上只接受 Boats 而没有抱怨的 class?这是一个错误吗?还是出于某种原因设计的?或者我可以用一些标志启用它吗?
链接的副本解释了这种情况。对于上面的代码,修复可能是使用 --strictFunctionTypes
并将您的方法签名编写为函数值-属性 签名:
interface InspectorClass{
inspect: (v:Vehicle) => void
}
示例如下:
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)
}
接口的契约声明 InspectorClass 实例中的检查方法必须能够检查任何类型的 Vehicle。为什么 TypeScript 让我实现一个实际上只接受 Boats 而没有抱怨的 class?这是一个错误吗?还是出于某种原因设计的?或者我可以用一些标志启用它吗?
链接的副本解释了这种情况。对于上面的代码,修复可能是使用 --strictFunctionTypes
并将您的方法签名编写为函数值-属性 签名:
interface InspectorClass{
inspect: (v:Vehicle) => void
}