【问题标题】:Typescript compiler selecting wrong overload打字稿编译器选择错误的重载
【发布时间】:2016-04-06 03:26:21
【问题描述】:

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 都是numbers,但是当我这样称呼它时:

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 使用第一个重载?

【问题讨论】:

    标签: node.js mongoose typescript overloading


    【解决方案1】:

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

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

    当方法期望时:

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

    你的回调应该是:

    }, (err, results) => {
    

    【讨论】:

    • DefinitelyTyped 中的.d.ts 文件似乎不适合此功能。回调参数应该是&lt;T&gt;(err: any, result: T[], stats: any) =&gt; void,但是你的回答是正确的。
    猜你喜欢
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多