打字稿编译器选择错误的重载

时间:2016-01-01 17:58:54

标签: node.js mongoose typescript overloading

mongoose.d.ts“DefinitelyTyped”文件中,geoNear函数有两个重载:

geoNear(point: { type: string; coordinates: number[] }, options: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;
geoNear(point: number[], options: Object, callback?: (err: any, res: T[]) => void): Query<T[]>;

我已将point定义为

const point = { type: "Point", coordinates: [lng, lat] }

其中lnglat都是number s,但是当我用它调用它时:

Location.geoNear(point, {
        spherical: true,
        maxDistance: theEarth.getRadiansFromDistance(maxDistance),
        num: 10
    }, (err, results, stats) => {
        var locations = []
        results.forEach((doc: any) => {
            locations.push({
                distance: theEarth.getDistanceFromRadians(doc.dis),
                name: doc.obj.name,
                address: doc.obj.address,
                rating: doc.obj.rating,
                facilities: doc.obj.facilities,
                _id: doc.obj._id
            })
        })
        res.status(200).json(locations)
    })

编译器抱怨

Argument of type '{ type: string; coordinates: number[]; }' is not assignable to parameter of type 'number[]'

如何强制tsc使用第一次重载?

1 个答案:

答案 0 :(得分:4)

您发送的回调需要3个参数,而不是接口中定义的2个参数。 你发送:

 }, (err, results, stats) => {

当方法需要时:

callback?: (err: any, res: T[]) => void

你的回调应该是:

}, (err, results) => {