[英]Typescript method overloading with one parameter of different type (non-primitive)
Ok, what I would like to do is simple. 好的,我想做的很简单。 I want to overload a method so that it can take one parameter, which is of non-primitive type. 我想重载一种方法,以便它可以采用一个非原始类型的参数。
I understand I can't do it like this because TypeScript losts all types when compiled to JavaScript. 我知道我不能这样做,因为TypeScript在编译为JavaScript时会丢失所有类型。 If one of the parameters was primitive (eg string), I could do it (typeof myString == "string"). 如果参数之一是原始的(例如字符串),我可以做到(typeof myString ==“ string”)。
public doSomething(typeA: TypeA);
public doSomething(typeB: TypeB);
public doSomething(type: TypeA | TypeB) {
if (typeof type == "TypeA") {
... // obviously I can't do that, Javascript got no types
... // typeof type === "object"
}
else if (typeof type == "TypeB") { //the same }
else { //undefined }
}
What I thought up is this: 我想到的是:
public doSomething(typeA?: TypeA, typeB?: TypeB) {
if (typeA) { ... }
else if (typeB) { ... }
else { //undefined }
}
Then I have to call this way: 然后我必须这样称呼:
doSomething(typeA, undefined); //to call TypeA version
doSomething(undefined, typeB); //to call TypeB version
Is such a design acceptable or is it better to rather create two separate methods? 这样的设计是否可以接受?还是最好创建两个单独的方法?
This notation is probably better. 这种表示法可能更好。 You are forced (by IDE) to add the undefined when you're calling the method. 调用该方法时,IDE强制您添加未定义的方法。
public doSomething(typeA: TypeA | undefined, typeB: TypeB | undefined) {
if (typeA) { ... }
else if (typeB) { ... }
else { //undefined }
}
You can have functions that check whether a value is of a certain type, and typescript has the notion of user defined type guards : 您可以具有检查某个值是否属于某种类型的函数,而typescript具有用户定义的类型guards的概念:
interface TypeA {
x: string;
}
function isTypeA(value: any): value is TypeA {
return Object.keys(value).length === 1 && typeof value.x === "string";
}
interface TypeB {
y: number;
}
function isTypeB(value: any): value is TypeB {
return Object.keys(value).length === 1 && typeof value.y === "number";
}
function doSomething(typeA: TypeA);
function doSomething(typeB: TypeB);
function doSomething(type: TypeA | TypeB) {
if (isTypeA(type)) {
console.log(type.x);
} else {
console.log(type.y);
}
}
( code in playground ) ( 操场上的代码 )
In your example, as the passed value can be only of TypeA
and TypeB
then there's no need for the extra if/else. 在您的示例中,由于传递的值只能是TypeA
和TypeB
因此不需要多余的if / else。
But you can also use the isTypeB
. 但是您也可以使用isTypeB
。
This method is good if you need this check in a few places in your code, but if you need it for just that one function, then I think that I would go with two different functions, depending on the amount of duplicated code. 如果您需要在代码中的几个地方进行此检查,那么这种方法是不错的选择,但是如果您只需要一个函数,那么我认为我会使用两个不同的函数,具体取决于重复代码的数量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.