【问题标题】:How can I add function typings for static method chaning in TypeScript?如何在 TypeScript 中为静态方法链接添加函数类型?
【发布时间】:2021-05-17 19:10:55
【问题描述】:

Image 我有这个带有 2 个静态方法的小类。像这样,我可以根据需要链接方法。

class MyClass {
  static x() {
    console.log("x");
    return this;
  }

  static y() {
    console.log("y");
    return this;
  }
}

MyClass.x().y();

如果我想为这 2 种方法添加分型,分型会是什么样子?换句话说,我怎样才能定义正确的返回类型?

class MyClass {
  static x(): MyClass {
    console.log("x");
    return this;
  }

  static y(): MyClass {
    console.log("y");
    return this;
  }
}

MyClass.x().y();

这不起作用,但希望能说明我的意思。

【问题讨论】:

  • 为什么需要定义任何类型?让编译器将其推断为typeof MyClass,您可以将其注释为if you really want to
  • 我知道它可以在不定义类型的情况下工作,但我只是想把它放在那里。天哪,谢谢!字面上忘记了 typeof :|

标签: typescript methods types static method-chaining


【解决方案1】:

名为MyClass类型对应于MyClass类的一个实例,因此没有x或@等静态方法987654327@.

在静态方法实现中,this 指的是 构造函数本身,它(只要您没有子类需要担心)将是 命名为MyClassMyClass 构造函数的类型不是MyClass,而是typeof MyClass,使用Typescript typeof type query operator

如果您在示例代码中使用 IntelliSense 检查为 x()y() 推断的返回类型,您将看到:

class MyClass {       
  // (method) MyClass.x(): typeof MyClass
  //     ↓
  static x() {
    console.log("x");
    return this;
  }
}

如果您出于某种原因真的想对类型进行注释,typeof MyClass 可能是正确的答案:

class MyClass {
  static x(): typeof MyClass {
    console.log("x");
    return this;
  }

  static y(): typeof MyClass {
    console.log("y");
    return this;
  }
}

请注意,如果您有子类并且想要捕获子类在静态方面也具有继承这一事实,那么事情会变得有些棘手:

class YourClass extends MyClass {
  static z = 123;
}

YourClass.x().z // error!
// ---------> ~
// not known to exist by TypeScript but exists at runtime

你可能不关心这个,但如果你这样做了,这在 TypeScript 中是一个突出的问题;有关讨论和解决方法,请参阅 microsoft/TypeScript#5863。可根据要求提供更多信息。


Playground link to code

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 1970-01-01
    • 2021-03-18
    • 2017-03-26
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    相关资源
    最近更新 更多