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

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

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

问题

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

interface CallOrConstruct {
  new (s: string): Date;
  (n?: number): number;
}

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

interface CallOrConstruct {
    new (s: string): { s: string }
    (n: number): number
}
function invokeF (fn: CallOrConstruct) {
    fn(5)
    new fn('hello world')
}

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

interface CallOrConstruct {
  new (s: string): Date;
  (n?: number): number;
}

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。

interface CallOrConstruct {
    new (s: string): { s: string }
    (n: number): number
}
function invokeF (fn: CallOrConstruct) {
    fn(5)
    new fn('hello world')
}

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:

const fn = function(this: any, x: any): any {
  if (new.target) {
    // we're in a constructor now
    this.s = x;
  } else {
    // a plain function call
    return x;
  }
} 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:

const fn = function(this: any, x: any): any {
  if (new.target) {
    // we're in a constructor now
    this.s = x;
  } else {
    // a plain function call
    return x;
  }
} 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:

确定