简体   繁体   English

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

[英]How to do dynamic signature and return type in Typescript?

I want to create a function behave like getter and setter based on if argument present.我想根据是否存在参数创建一个类似于 getter 和 setter 的函数。 The logic is already in the function, but TS can not figure the type out and complains.逻辑已经在函数里了,但是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(p){
  if (arguments.length === 0) return this._cursor
  this._cursor = p
  return this
}

You are very close.你很亲近。 Your argument type for your method that has the implementation has to be compatible with all overloads.具有实现的方法的参数类型必须与所有重载兼容。 In this case you have account for the argument being optional.在这种情况下,您可以考虑参数是可选的。

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
}

Note that you also need a non-null assertion on p once you know it is defined.请注意,一旦您知道 p 已定义,您还需要对 p 进行非空断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM