我有一个多类型变量的问题,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'.你能帮我吗,我哪里做错了。
谢谢。
发布于 2020-10-14 00:36:41
问题是,如果msg不是数组,则msg的类型被推断为string | Message。将其放入数组中会使该数组隐式为(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[];https://stackoverflow.com/questions/64339275
复制相似问题