pio*_*eqd 3 casting type-conversion type-assertion typescript angular
假设我有两个接口,它们有两个相同的成员 id 和名称:
export interface InterfaceA {
id: number;
name: string;
//some other members
}
export interface InterfaceB {
id: number;
name: string;
//some other members
}
Run Code Online (Sandbox Code Playgroud)
我想获取这两种类型的元素的集合来填充一些组合框。我需要每个元素的 id、名称和类型,所以我制作了以下课程
export class AssignableDevice {
id: number;
name: string;
type: string;
constructor(device: InterfaceA | InterfaceB) {
this.id = device.id;
this.name = device.name;
this.type = typeof device; //still returns "object"
}
}
// in onInit method :
ngOnInit() {
super.ngOnInit();
this.dataService.getInterfaceA().subscribe((data) => {
data.forEach((element) => this.devices.push(new AssignableDevice(element as InterfaceA)));
});
this.dataService.getInterfaceB().subscribe((data) => {
data.forEach((element) => this.devices.push(new AssignableDevice(element as InterfaceB)));
})
}
Run Code Online (Sandbox Code Playgroud)
但问题是我总是在“AssignableDevice”类构造函数中得到“对象”,而且我不知道为什么会发生这种情况。我可以通过使用一些枚举来实现我的目标,但我想知道为什么这个解决方案不起作用,以及如何实现这一目标。我不想对 InterfaceA 或 InterfaceB 进行任何更改。
您无法在运行时访问对象的 TypeScript 类型(一般情况下)。TypeScript 提供了编译时类型系统。您typeof使用的是 JavaScript运行时 typeof,它始终返回"object"任何类型的对象(以及null)。
您已经说过您想将类型发送到后端,因此您在运行时肯定需要它。我可以看到至少有两种方法可以做到这一点:
您可以将接口定义为品牌接口,以确保始终包含以下类型:
export interface InterfaceA {
id: number;
name: string;
//some other members
type: "InterfaceA"; // <== This is a _string literal type_ whose only valid value is the string "InterfaceA"
}
export interface InterfaceB {
id: number;
name: string;
//some other members
type: "InterfaceB"; // <=== String literal type
}
Run Code Online (Sandbox Code Playgroud)
现在,分配给类型的变量、属性或参数的任何对象都InterfaceA必须具有type带有字符串"InterfaceA"和类似的属性InterfaceB。然后您的代码将使用该type属性。
您可以将构造函数设为私有,并且只允许通过createX接口的方法进行创建:
export class AssignableDevice {
id: number;
name: string;
type: string;
private constructor(device: InterfaceA | InterfaceB, type: string) {
this.id = device.id;
this.name = device.name;
this.type = type;
}
static createA(device: InterfaceA): AssignableDevice {
return new AssignableDevice(device, "InterfaceA");
}
static createB(device: InterfaceB): AssignableDevice {
return new AssignableDevice(device, "InterfaceB");
}
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以使用适合createX您所拥有的对象类型的方法。由于您在编写代码时做出了选择,TypeScript 可以进行类型检查以查看您是否将正确类型的对象传递给createX.
| 归档时间: |
|
| 查看次数: |
1069 次 |
| 最近记录: |