微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

关于 TypeScript 联合类型的困惑

如何解决关于 TypeScript 联合类型的困惑

我希望对象 (groupItems) 的某个属性是字符串数组或对象数组,因此我创建了以下接口:

 interface PanelItem {
      groupTitle: string;
      groupItems: string[] | {text: string,type: string}[];
    }

我创建了一个 TypeScript 变量 panelContent: PanelItem[] = [] 并尝试向其中添加项目

this.panelContent.push({groupTitle: 'abc',groupItems: ['item3',{text: 'item',type: 'action'},'item4']});

但 TypeScript 抱怨这句话

TS2322: Type '(string | { text: string; type: string; })[]' is not assignable to type 'string[] | { text: string; type: string; }[]'. 
  Type '(string | { text: string; type: string; })[]' is not assignable to type 'string[]'. 
    Type 'string | { text: string; type: string; }' is not assignable to type 'string'. 
      Type '{ text: string; type: string; }' is not assignable to type 'string'. 

所以我把界面改成了

 interface PanelItem {
          groupTitle: string;
          groupItems: (string | {text: string,type: 'action'})[];
        }

和 TypeScript 不再抱怨。 有人可以解释一下这两种界面语法之间的区别吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。