我有一个函数参数,它接受两种类型:string | string[]
。我将此参数用于仅接受string
类型的烤面包机服务,因此当我使用join(' ')
时出现错误:Property 'join' does not exist on type 'string | string[]'. Property 'join' does not exist on type 'string'.
并且无法编译应用程序。 / p>
showToaster(msg: string, customClass: string | string[]) {
let cstmClass: any;
switch (typeof customClass) {
case 'string':
cstmClass = customClass;
break;
case 'object':
cstmClass = customClass.join(' ');
break;
}
this.toastrService.show(msg, null, {
toastClass: cstmClass,
timeOut: 3500
});
}
答案 0 :(得分:1)
使用Array.isArray确定类型:
if(Array.isArray(customClass)) {
cstmClass = customClass.join(' ');
}
else {
cstmClass = customClass;
}
编译数组的原因是|
选项仅公开两种类型共享的属性和方法。检查类型是否为object
不起作用的原因是因为object
没有join
方法。