英文:
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;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论