簡體   English   中英

在 angular html 模板中檢查具有數組類型的聯合類型變量的長度時出現產品構建問題

[英]Prod build issue while checking the length of union type variable having array type in angular html template

我在檢查聯合類型數組、字符串和數字的長度時遇到問題。 在 prod 模式下構建 angular 項目時的問題示例代碼:

ts 中的變量

public developerData: {
    [key: string]: {
        type: 'default';
        data: string | number;
    } | {
        type: 'array',
        data: Array < string | number | boolean >
    }
} = {
    'test': {
        'type': 'array',
        'data': ['1', '2', '3']
    }
};

Html 模板

<div *ngIf="developerData['test']['type']=='array' && developerData['test']['data'].length >= 0">
   Welcome
</div>

產品構建錯誤

類型“字符串”上不存在屬性“長度”| 號碼 | (字符串 | 數字 | 布爾值)[]'。 類型“數字”上不存在屬性“長度”。

軟件版本

  • Angular:7.3.5

  • TypeScript:3.1.6

  • 節點:10.16.3

  • NPM:6.9.0

訪問變量時,它可以是“字符串”(或)“數字”(或)“布爾值”,同時您使用“|”指定在 typescript 中。

因此,在訪問變量的“長度”屬性之前,在 JS 中使用“typeof”方法添加類型檢查。

您可以在“tsx”文件中使用驗證器 function 來檢查類型並返回正確的驗證結果並在“ngif”中調用它

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM