如何在 TypeScript 中定义同时包含调用和构造签名的函数实现。

huangapple go评论107阅读模式
英文:

How to define implementation of function that combine call and construct signatures in typescript

问题

typescript文档讨论了函数的组合调用和构造签名,并描述了如何声明类型。https://www.typescriptlang.org/docs/handbook/2/functions.html

  1. interface CallOrConstruct {
  2. new (s: string): Date;
  3. (n?: number): number;
  4. }

但它从未展示如何定义这种函数的实际实现。我的英语不好,所以我制作了一个示例来描述我的问题,我将感谢你的回答。

  1. interface CallOrConstruct {
  2. new (s: string): { s: string }
  3. (n: number): number
  4. }
  5. function invokeF (fn: CallOrConstruct) {
  6. fn(5)
  7. new fn('hello world')
  8. }
  9. var fn: CallOrConstruct // 如何定义fn的实际实现
英文:

The typescript documentation talks about function combine call and construct signatures。and describes how you can declare the type。https://www.typescriptlang.org/docs/handbook/2/functions.html

  1. interface CallOrConstruct {
  2. new (s: string): Date;
  3. (n?: number): number;
  4. }

But it never shows how to define the actual implementation of such functions。 my english's not good, so I make a sample to descript my question, I will appreciate your answer。

  1. interface CallOrConstruct {
  2. new (s: string): { s: string }
  3. (n: number): number
  4. }
  5. function invokeF (fn: CallOrConstruct) {
  6. fn(5)
  7. new fn('hello world')
  8. }
  9. var fn:CallOrConstruct // how to define the actual implementation of fn

I want to know how to define the actual implementation of the type that combine call and construct signature。

答案1

得分: 0

You'd use new.target to distinguish between the calls. But you'll basically have to implement an overloaded function which requires liberal use of any to get it to compile as TypeScript:

  1. const fn = function(this: any, x: any): any {
  2. if (new.target) {
  3. // we're in a constructor now
  4. this.s = x;
  5. } else {
  6. // a plain function call
  7. return x;
  8. }
  9. } as CallOrConstruct;
英文:

You'd use new.target to distinguish between the calls. But you'll basically have to implement an overloaded function which requires liberal use of any to get it compile as TypeScript:

  1. const fn = function(this: any, x: any): any {
  2. if (new.target) {
  3. // we're in a constructor now
  4. this.s = x;
  5. } else {
  6. // a plain function call
  7. return x;
  8. }
  9. } as CallOrConstruct;

huangapple
  • 本文由 发表于 2023年2月19日 16:02:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/75498754.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定