Javascript 如何用Angular 4解决metod过度编码问题,使用不同的数据类型?
这是我的演示代码:Javascript 如何用Angular 4解决metod过度编码问题,使用不同的数据类型?,javascript,angular,typescript,Javascript,Angular,Typescript,这是我的演示代码: class First { x: string; y: string; constructor() { } setValue(x: string, y: string): void { this.x = x; this.y = y; console.log("setValue In A value of x and y:", this.x, this.y); }
class First {
x: string;
y: string;
constructor()
{
}
setValue(x: string, y: string): void {
this.x = x;
this.y = y;
console.log("setValue In A value of x and y:", this.x, this.y);
}
getValue(): void {
console.log("getValue In A value of x and y:", this.x, this.y);
}
}
class Second extends First {
x: string = '5';
z: number;
constructor() {
super();
}
setValue(z: number, y: string) {
this.z = z;
this.y = y;
return super.setValue(this.x, this.y);
}
}
我有两节课,第一节和第二节。
但在第二节课上,我犯了错误
类型“Second”中的属性“setValue”不能分配给同一个属性
基类型“First”中的属性。键入“(z:number,y:string)=>void”
不可分配给类型“(x:string,y:string)=>void”。
参数“z”和“x”的类型不兼容。
类型“string”不能分配给类型“number”
我尝试了一些可能的解决方案,在Class-first方法中将type指定为“any”
还尝试了另一个补丁,将第二个类中的联合类型指定为z:string | number
但这两种解决方案都是对问题的拼凑,但无法解决原始问题,因为我们可以传递字符串或数字,但实际上,它只接受字符串。
如果假设该方法只接受一个参数,则上述任何解决方案都不起作用
我希望我的问题已经很清楚了。问题是,您试图做的事情违反了OOP原则。假设您想要的过载将被允许考虑流动代码:
let f: First = new Second() // Assign a derived class to a base type reference
f.setValue("Not a number", "y") // Second is getting a string insead of a number
在上面的代码中,第二个
将收到一个字符串而不是一个数字作为第一个参数,因为我们是通过基类引用调用的
一种解决方案是保留原始签名和添加带有数字的签名,并确保两者都按预期工作:
class First {
x: string;
y: string;
constructor()
{
}
setValue(x: string, y: string): void {
this.x = x;
this.y = y;
console.log("setValue In A value of x and y:", this.x, this.y);
}
getValue(): void {
console.log("getValue In A value of x and y:", this.x, this.y);
}
}
class Second extends First {
x: string = '5';
z: number;
constructor() {
super();
}
setValue(x: string, y: string)
setValue(z: number, y: string)
setValue(xz: string | number, y: string) {
if (typeof xz == 'number') {
this.z = xz; // xz is number so we got called with z
this.y = y;
return super.setValue(this.x, this.y);
} else {
// xz is string so we got called with x
return super.setValue(xz, y);
}
}
}
let f: First = new Second() // Assign a derived class to a base type reference
f.setValue("Not a number", "y") // Works as expected now
通常,在派生类时,可以将其添加到类的公共签名中,但不能从中获取,因为这样会破坏OOP的租户,从而可以安全地将派生类分配给基类引用
注意Typescript的类型非常灵活,您可以进行一些类型手术,从第一个中删除设置值
,以便在第二个中拥有更高的自由度。我可以提供这样的解决方案,但我强烈建议不要这样做。此解决方案仅在第一种情况下有效,如果参数类型发生更改,但在第二种情况下,如果从子类方法中删除参数,则将失败。下面给出的代码只是一个示例,用于说明typescript中面临的问题。不确定您的意思。您可以使用更少参数的重载,只需更改实现签名:setValue(x:string,y:string)setValue(z:number)setValue(xz:string | number,y?:string){…}