Angular 类型脚本类型';字符串| Message |(字符串[]| Message[])[]和#x27;不可分配给类型';字符串[]|消息[]和#x27;
我对多类型变量有问题,Angular 类型脚本类型';字符串| Message |(字符串[]| Message[])[]和#x27;不可分配给类型';字符串[]|消息[]和#x27;,angular,typescript,Angular,Typescript,我对多类型变量有问题,InputMessage声明是: export type InputMessage = Message | string | Message[] | string[]; 我是这样用的: private addMessage(msg: InputMessage, type: 'ERROR' | 'WARN' | 'INFO' | 'SUCCESS') { if (!msg) return; const arrayMsg: Message[] | str
InputMessage
声明是:
export type InputMessage = Message | string | Message[] | string[];
我是这样用的:
private addMessage(msg: InputMessage, type: 'ERROR' | 'WARN' | 'INFO' | 'SUCCESS') {
if (!msg) return;
const arrayMsg: Message[] | string[] = msg instanceof Array ? msg : [msg];
arrayMsg.forEach((item) => {
this.message(item, type);
})
}
但我在编译时有一个错误:
ERROR in src/app/components/growl/growl.service.ts(52,11): error TS2322: Type '(string | Message)[]' is not assignable to type 'string[] | Message[]'.
Type '(string | Message)[]' is not assignable to type 'string[]'.
Type 'string | Message' is not assignable to type 'string'.
Type 'Message' is not assignable to type 'string'.
你能帮我一下吗,我哪里做错了
谢谢。问题是,如果
msg
不是数组,那么msg
的类型将被推断为string | Message
。将其放入数组会使该数组隐式地(string | Message)[
防止此错误的一种方法是进行第二次类型检查,以允许编译器检查字符串
或消息
:
const arrayMsg: Message[] | string[] = msg instanceof Array ? msg : (typeof(msg) === 'string' ? [msg] : [msg]);
另一种方法是显式地将类型转换为[msg]
:
const arrayMsg2: Message[] | string[] = msg instanceof Array ? msg : [msg] as Message[] | string[];
问题是,如果
msg
不是数组,那么msg
的类型将被推断为string | Message
。将其放入数组会使该数组隐式地(string | Message)[
防止此错误的一种方法是进行第二次类型检查,以允许编译器检查字符串
或消息
:
const arrayMsg: Message[] | string[] = msg instanceof Array ? msg : (typeof(msg) === 'string' ? [msg] : [msg]);
另一种方法是显式地将类型转换为[msg]
:
const arrayMsg2: Message[] | string[] = msg instanceof Array ? msg : [msg] as Message[] | string[];