Javascript 如何在Typescript中进行动态签名和返回类型?

Javascript 如何在Typescript中进行动态签名和返回类型?,javascript,typescript,Javascript,Typescript,我想基于if参数创建一个类似getter和setter的函数。逻辑已经在函数中,但TS无法识别类型并进行投诉 // if no argument, is a getter, and return `Coord` type cursor(): Coord // if present, is a setter, return `this` type cursor(p: Coord): this 你很接近。具有实现的方法的参数类型必须与所有重载兼容。在这种情况下,您必须说明参数是可选的 curso

我想基于if参数创建一个类似getter和setter的函数。逻辑已经在函数中,但TS无法识别类型并进行投诉

// if no argument, is a getter, and return `Coord` type
cursor(): Coord

// if present, is a setter, return `this` type
cursor(p: Coord): this

你很接近。具有实现的方法的参数类型必须与所有重载兼容。在这种情况下,您必须说明参数是可选的

cursor(): Coord
cursor(p: Coord): this
cursor(p?: Coord) { // p has to be optional
    if (arguments.length === 0) return this._cursor
    this._cursor = p!; // non-null assertion
    return this
}

请注意,一旦知道p已定义,您还需要在p上使用非空断言。

您刚刚保存了我的一天!我对if(arguments.length==0 | | p==undefined)做了一些修改。很高兴听到这个消息。请注意,它的实际工作方式会发生变化,这取决于是否支持将值设置为未定义。非null断言是一种仅类型检查,对运行时代码没有影响。
cursor(): Coord
cursor(p: Coord): this
cursor(p?: Coord) { // p has to be optional
    if (arguments.length === 0) return this._cursor
    this._cursor = p!; // non-null assertion
    return this
}