首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Typescript类型'string | Message | (string[] | Message[])[]‘不能赋值给类型'string[] | Message[]’

Typescript类型'string | Message | (string[] | Message[])[]‘不能赋值给类型'string[] | Message[]’
EN

Stack Overflow用户
提问于 2020-10-14 00:24:05
回答 1查看 126关注 0票数 1

我有一个多类型变量的问题,InputMessage声明是:

代码语言:javascript
复制
export type InputMessage = Message | string | Message[] | string[];

我这样使用它:

代码语言:javascript
复制
  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);
    })
  }

但是我在编译时有一个错误:

代码语言:javascript
复制
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'.

你能帮我吗,我哪里做错了。

谢谢。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-14 00:36:41

问题是,如果msg不是数组,则msg的类型被推断为string | Message。将其放入数组中会使该数组隐式为(string | Message)[]

防止此错误的一种方法是进行第二次类型检查,以允许编译器检查stringMessage

代码语言:javascript
复制
const arrayMsg: Message[] | string[] = msg instanceof Array ? msg : (typeof(msg) === 'string' ? [msg] : [msg]);

另一种方法是显式地将该类型转换为[msg]

代码语言:javascript
复制
const arrayMsg2: Message[] | string[] = msg instanceof Array ? msg : [msg] as Message[] | string[];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64339275

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档