gpt4 book ai didi

javascript - typescript 重载类方法 - 相同的返回类型,不同的参数

转载 作者:数据小太阳 更新时间:2023-10-29 04:07:54 29 4
gpt4 key购买 nike

我有一个 typescript 类:

class ContactModel {

public getUsage(type: string): restangular.IElement {
return this.getBase().one('usages', type);
}

public getUsage(customerId: number, type: string): restangular.IElement {
return this.ModelFactory.createRequestMapper(ContactModel.options)
.one('customers', customerId).all('contacts/usages', type);
}

//...
}

这会导致编译器抛出以下错误:

>> app/modules/common/model/ContactModel.ts(27,12): error TS2393: Duplicate function implementation.
>> app/modules/common/model/ContactModel.ts(31,12): error TS2393: Duplicate function implementation.

我看到此示例与 TypeScript Handbook 之间的唯一区别是他们的例子有不同的返回类型,而我有相同的返回类型(两种情况都有不同的输入参数)。

问题是:我做错了什么 - 或者 typescript 类方法是否需要具有不同的方法参数类型以允许重载?这看起来很愚蠢,因为 .Net 和 Java 都支持具有相同返回类型和不同输入类型的重载。

最佳答案

JavaScript 不做运行时类型信息,所以你必须自己做重载消歧。请注意,在手册中的示例中,只有一个函数实现,而您有两个。

class ContactModel {
public getUsage(type: string): restangular.IElement;
public getUsage(customerId: number, type: string): restangular.IElement;
public getUsage(typeOrCustomerId: string|number, type?: string): restangular.IElement {
if (typeof typeOrCustomerId === 'string') {
// First overload
return this.getBase().one('usages', type);
} else {
// Second overload
return this.ModelFactory.createRequestMapper(ContactModel.options)
.one('customers', customerId).all('contacts/usages', type);
}
}
}

关于javascript - typescript 重载类方法 - 相同的返回类型,不同的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31810881/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com