使用 TypeScript 重载时出现“期望有 0 个参数,但有 2 个参数”的错误。

5

我有一个带有重载方法的类(两个版本)。

其中一个版本不带参数,另一个版本可以接受两个参数。

class DFD {
...
    getEndDatetime(): string; 
    getEndDatetime(startTime?: string, duration?: number): string {
        if (!startTime || !duration) {
            return new Date(this.getEndDatetimePOSIX()).toLocaleString();
        } else {
            this.getEndDatetimePOSIX(startTime, duration);
            return new Date(this.getEndDatetimePOSIX(startTime, duration)).toLocaleString();
        }
    }
...
}

当我调用 this.getEndDateTime("8/11/2019, 11:42:17 PM", 5)时,TypeScript 给出了一个错误提示:"Expected 0 arguments, but got 2." 我该如何满足 TypeScript 的要求?
我正在运行 Node v10.16.0,使用 TypeScript v3.5.2。我尝试过调换函数重载的顺序:
// Switch the order
...
    getEndDatetime(startTime?: string, duration?: number): string;
    getEndDatetime(): string { 
        ...
    }
...

TypeScript 突出显示了代码中的 startTimeduration,并表示找不到它们。
我期望我的第一个重载实现在使用两个参数进行调用时不会引发任何错误,但是它确实引发了错误。
从其他地方的解读建议表明我的代码应该通过。

为什么在两个参数都是可选的情况下,您列出了无参重载? - Jeff Bowman
仅保留没有空参数的第二个声明。 - Mochamad Arifin
@JeffBowman 考虑后发现这并非必要。一个原因可能是文档,但在我的情况下不实用。另一个原因是强调两种实现方式(重载语法澄清了它是0个参数或2个参数。仅使用可选参数会使其模糊,无法确定应该使用0、1还是2个参数)。我提出问题的基础是为了更好地理解TypeScript。当我使用看似有效的重载语法时,为什么在调用方法时会给我错误?“无参数重载”是否不被允许? - user11104582
1个回答

2
很可能是因为转译器无法确定你想调用哪个方法,因为两个参数的签名是可选的。换句话说,getEndDateTime() 可以指代你定义的任一签名。要支持此功能,您需要使 startTimeduration 不再是可选的。"最初的回答"
getEndDatetime(): string; 
getEndDatetime(startTime: string, duration: number): string; 
getEndDatetime(startTime?: string, duration?: number): string {
    if (!startTime || !duration) {
        return new Date(this.getEndDatetimePOSIX()).toLocaleString();
    } else {
        this.getEndDatetimePOSIX(startTime, duration);
        return new Date(this.getEndDatetimePOSIX(startTime, duration)).toLocaleString();
    }
}

哦,所以最后一个 getEndDatetime 是实际的实现,前两个是签名。因此,您永远不会有少于三个 funcNames(或 getEndDate())的方法/函数重载任何情况。在我的情况下,我只给了它一个没有参数的签名。您代码中的第二行添加了第二个选项,使得我的带有两个参数的方法调用有效。 - user11104582

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接