0

I am facing an issue while checking the length of union type array, string and number. Sample code of issue while build angular project in prod mode:

Variable in 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 template

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

Prod build error

Property 'length' does not exist on type 'string | number | (string | number | boolean)[]'. Property 'length' does not exist on type 'number'.

Software versions

  • Angular: 7.3.5

  • TypeScript: 3.1.6

  • Node: 10.16.3

  • NPM: 6.9.0

Nelson Gnanaraj
  • 176
  • 1
  • 13

1 Answers1

0

While accessing the variable it can either be a 'string' (or) 'number' (or) 'boolean' at the same time as you have specified using '|' in typescript.

So before accessing 'length' property of the variable add a type check using 'typeof' method in JS.

You can use a validator function in 'tsx' file that checks the type and returns proper validation result and call that in 'ngif'

Viswa
  • 1
  • Is possible to check without typescript validation. I have to check this within HTML tag. – Nelson Gnanaraj Mar 25 '21 at 05:38
  • You can write nested conditional statements inside ngif if you want, but that would make it harder to debug. But you can call a validator function in ngIf like
    Welcome
    – Viswa Mar 25 '21 at 05:49
  • Can you please share some possible code snippet – Nelson Gnanaraj Mar 25 '21 at 05:51
  • https://stackoverflow.com/questions/51674156/angular-ngif-binding-to-function - Refer this question for different Implementations – Viswa Mar 25 '21 at 05:52
  • I want validation without calling ts methods. While scrolling the page, the method called many times. it may cause page hanging. – Nelson Gnanaraj Mar 25 '21 at 05:57
  • Globals like Window, typeof are not available within a template as Angular only parses Angular templates and not JS templates. You need to use that within a Component Typescript. But if you want to optimize you can use memoization – Viswa Mar 25 '21 at 06:25