Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angular 将instanceof与typescript联合使用类型CustomObject | CustomObject[]_Angular_Typescript - Fatal编程技术网

Angular 将instanceof与typescript联合使用类型CustomObject | CustomObject[]

Angular 将instanceof与typescript联合使用类型CustomObject | CustomObject[],angular,typescript,Angular,Typescript,我目前正在尝试为组件输入实现联合类型 @Input('role')角色:角色|角色[] 角色在哪里 enum Role { /**/ } 但是,当我在代码后面使用变量时 userHasRole(role:role):布尔值 if(userHasRole(this.role)){/**} 它抛出一个错误,因为角色是数组或单个对象,并且该方法只允许单个对象 为了解决这个问题,我将代码包装在一个if语句中,使用instanceof进行检查 if (this.role instanceof Role)

我目前正在尝试为组件输入实现联合类型

@Input('role')角色:角色|角色[]

角色在哪里

enum Role { /**/ }
但是,当我在代码后面使用变量时

userHasRole(role:role):布尔值

if(userHasRole(this.role)){/**}

它抛出一个错误,因为角色是数组或单个对象,并且该方法只允许单个对象

为了解决这个问题,我将代码包装在一个if语句中,使用instanceof进行检查

if (this.role instanceof Role) { 
   if (userHasRole(this.role) { /**/ }
}
但是类型检查器仍然在抛出错误,可能是一个数组,我如何才能避开这个问题

我从方法调用中得到了两个错误

ts2345类型为“Role | Role[]”的参数不能分配给类型为“Role”的参数。类型“Role[]”不能分配给类型“Role”。

从支票的那一刻起


ts2359“instanceof”表达式的右侧必须是“any”类型或可分配给“Function”接口类型的类型。

您不能将
instanceof
表达式与
枚举一起使用。如果
Role
是一个类,它就可以工作

您可以使用
Array.isArray()
检查它是数组还是单个值,TS将正确地缩小控制流中的类型

例如:

if (!Array.isArray(this.role)) {
  // In here this.role has type Role
  if (userHasRole(this.role)) { /**/ }
} else {
  // In here this.role has type Role[] so you could do something like:
  if (this.role.includes(Role.SOME_ROLE)) { /**/ }
}

PS-我认为
userhasprole
应该接受
Role | Role[]

您应该始终编写准确的错误消息,嗯,我无法重现。如果需要有意义的帮助,请确保发布。好的,我添加了错误消息,还添加了类型为枚举,您不能将
instanceof
enum
类型一起使用。我很惊讶您没有收到与
此相关的错误。role instanceof role
。您应该能够使用
Array.isArray(this.role)
。@Aaron这就是我遇到错误的地方,是否有其他方法可以做到这一点,或者我必须将输入切换为仅接受数组?是否有可能在其位置使用…args?谢谢!我最终在
userHasRole
方法中实现了这个逻辑,这样我们以后就可以轻松地在不同的领域实现它了!