【问题标题】:Union Types in Array - TypeScript don't show errors数组中的联合类型 - TypeScript 不显示错误
【发布时间】:2018-09-28 11:09:38
【问题描述】:

我正在使用 TypeScript 2.8.1 处理 Angular 5 中的菜单。

我想向验证传入配置添加类型,但是当我添加不正确的属性(例如,不需要的数据)时没有任何反应。

为什么 TS 不显示错误?

示例代码:

type MenuElement = MenuGroup | MenuItem;

interface MenuGroup {
    id: number;
    name: string;
    icon?: string;
    items: MenuItem[];
}

interface MenuItem {
    id: number;
    name: string;
    url: string;
}

const menuData = [
    {
        id: 1,
        name: 'category',
        icon: 'star',
        items: [
            {
                id: 1,
                name: 'subcategoryOne',
                url: 'urlOne'
            },
            {
                id: 2,
                name: 'subcategoryTwo',
                url: 'urlTwo'
            }
        ]
    },
    {
        id: 2,
        name: 'categoryTwo',
        url: 'urlThree',
        undesirableData: 'text' // undesirable data 
    }
];

export class MainComponent {
    public appMenu: Array<MenuElement>;

    constructor() {
        this.appMenu = this.createMenu(menuData);
    }

    createMenu(menu: Array<MenuElement>) {
        return menu;
    }
}

【问题讨论】:

    标签: typescript types typescript2.8


    【解决方案1】:

    要验证您正在创建的对象字面量,您需要在const 上实际指定类型,否则将根据使用情况推断出 const 类型。

    const menuData: MenuElement[] = [ ... ];
    

    当您传递调用 this.createMenu(menuData) 时不会出现错误,因为 menuDataMenuElement[] 兼容,即使它确实有一些额外的字段,对象文字仅在创建时才验证额外属性。比如:

    let o  = {
        id: 2,
        name: 'categoryTwo',
        url: 'urlThree',
        undesirableData: 'text'
    }
    let m :MenuItem = o;  //valid structurally compatible
    
    let m2: MenuItem  = { // invalid literal is checked for extra properties
        id: 2,
        name: 'categoryTwo',
        url: 'urlThree',
        undesirableData: 'text' 
    }
    

    如果您指定具有不兼容类型的已知属性,如果存在类型不兼容,您将收到错误,但如果您将对象字面量分配给明确键入为 @987654327 的变量/参数/字段,您只会收到额外属性的错误@

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-08-01
      • 2020-12-16
      • 1970-01-01
      • 2021-11-28
      • 2020-02-25
      • 2022-06-10
      • 2021-06-04
      相关资源
      最近更新 更多