为什么TypeScript允许方法参数中的隐式向下转换? [重复]

问题描述 投票:0回答:1

这里是示例:

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)
}

TypeScript Playground

接口的合同规定,InspectorClass实例中的检查方法必须能够检查任何类型的Vehicle。为什么TypeScript可以让我实现一个实际上只接受Boats而不会抱怨的类?这是错误吗?还是出于某种原因而设计?还是可以通过一些标志启用它?

typescript downcast
1个回答
0
投票

链接的重复项说明了这种情况。对于上面的代码,解决方法可能是使用--strictFunctionTypes并将方法签名写为函数值属性签名:

interface InspectorClass{
    inspect: (v:Vehicle) => void
}

Playground link

© www.soinside.com 2019 - 2024. All rights reserved.