【发布时间】:2019-04-20 10:06:59
【问题描述】:
关于函数重载如何在 Typescript 中工作存在很多问题(例如,TypeScript function overloading)。但是没有诸如“为什么它会以这种方式工作?”之类的问题。 现在函数重载看起来像这样:
function foo(param1: number): void;
function foo(param1: number, param2: string): void;
function foo(...args: any[]): void {
if (args.length === 1 && typeof args[0] === 'number') {
// implementation 1
} else if (args.length === 2 && typeof args[0] === 'number' && typeof args[1] === 'string') {
// implementation 2
} else {
// error: unknown signature
}
}
我的意思是,Typescript 的创建是为了让程序员的生活更轻松,它添加了一些所谓的“语法糖”,它提供了 OOD 的优势。那么为什么 Typescript 不能代替程序员来做这些烦人的事情呢?例如,它可能看起来像:
function foo(param1: number): void {
// implementation 1
};
function foo(param1: number, param2: string): void {
// implementation 2
};
foo(someNumber); // result 1
foo(someNumber, someString); // result 2
foo(someNumber, someNumber); // ts compiler error
并且这个 Typescript 代码会被转换成下面的 Javascript 代码:
function foo_1(param1) {
// implementation 1
};
function foo_2(param1, param2) {
// implementation 2
};
function foo(args) {
if (args.length === 1 && typeof args[0] === 'number') {
foo_1(args);
} else if (args.length === 2 && typeof args[0] === 'number' && typeof args[1] === 'string') {
foo_2(args);
} else {
throw new Error('Invalid signature');
}
};
而且我没有找到任何原因,为什么 Typescript 不能这样工作。有什么想法吗?
【问题讨论】:
-
"但是没有诸如“为什么它会以这种方式工作?”之类的问题。” AFAICS,这可能是因为“为什么”问题往往很快陷入猜测和意见,除非(有时甚至在之后)有人从语言架构师那里找到一个离散的报价。 (即使排除这一点,我也不知道 SO 是否真的针对“为什么”问题而设计,但我可能错了。)
-
@underscore_d,我没有找到这个奇怪问题的特殊资源。不过,我终于在下面找到了答案。
标签: typescript oop overloading