InterviewHubPRO
Section Overview
Q89

Question 89 of 283

Part 4: JIT vs AOT Compilation, Metadata & TypeScript (76 - 100)

31%
Angular & Signals (283 Qs)•Part 4: JIT vs AOT Compilation, Metadata & TypeScript (76 - 100)

Give an example of few metadata errors?

Below are some of the errors encountered in metadata,

  1. Expression form not supported: Some of the language features outside of the compiler's restricted expression syntax used in angular metadata can produce this error. Let's see some of these examples,
javascript
 1. export class User { ... }
    const prop = typeof User; // typeof is not valid in metadata
 2. { provide: 'token', useValue: { [prop]: 'value' } }; // bracket notation is not valid in metadata
  1. Reference to a local (non-exported) symbol: The compiler encountered a referenced to a locally defined symbol that either wasn't exported or wasn't initialized. Let's take example of this error,
javascript
 // ERROR
 let username: string; // neither exported nor initialized

 @Component({
   selector: 'my-component',
   template: ... ,
   providers: [
     { provide: User, useValue: username }
   ]
 })
 export class MyComponent {}

You can fix this by either exporting or initializing the value,

javascript
 export let username: string; // exported
 (or)
 let username = 'John'; // initialized
  1. Function calls are not supported: The compiler does not currently support function expressions or lambda functions. For example, you cannot set a provider's useFactory to an anonymous function or arrow function as below.
javascript
  providers: [
     { provide: MyStrategy, useFactory: function() { ... } },
     { provide: OtherStrategy, useFactory: () => { ... } }
   ]

You can fix this with exported function

javascript
 export function myStrategy() { ... }
 export function otherStrategy() { ... }
 ... // metadata
 providers: [
     { provide: MyStrategy, useFactory: myStrategy },
     { provide: OtherStrategy, useFactory: otherStrategy },
  1. Destructured variable or constant not supported: The compiler does not support references to variables assigned by destructuring. For example, you cannot write something like this:
javascript
 import { user } from './user';

 // destructured assignment to name and age
 const {name, age} = user;
 ... //metadata
 providers: [
     {provide: Name, useValue: name},
     {provide: Age, useValue: age},
   ]

You can fix this by non-destructured values

javascript
 import { user } from './user';
 ... //metadata
 providers: [
     {provide: Name, useValue: user.name},
     {provide: Age, useValue: user.age},
   ]