Angular 14: Trouble with ngFor after latest update - Type 'unknown' causing issues

Just updated my project to angular version 14.0.4

Within the html of a component, I have the following code:

<div class="file" *ngFor="let file of localDocumentData.files; index as i;">
      <div class="card">
           <img src={{file.thumbnail}} alt={{file.file_name}}>
           <p>{{file.file_name}}</p>
           <p>{{ file.file_size | bytes: false }}</p>
      </div>
 </div>

An error message is highlighting all object properties in the ngFor loop:

Object is of type 'unknown'.ngtsc(2571)

The files array is fetched from an API as part of an object. In the typescript file, the initialization of the file object is:

localDocumentData: any;

Despite no issues with building the project locally, the code continues to be highlighted.

Here is a screenshot of the highlighting

tsconfig.json

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "sourceMap": true,
    "declaration": false,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "target": "es2020",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ],
    "useUnknownInCatchVariables": false
  },
  "angularCompilerOptions": {
    "enableI18nLegacyMessageIdFormat": false,
    "strictInjectionParameters": true,
    "strictInputAccessModifiers": true,
    "strictTemplates": true
  }
}

Answer №1

To enhance the type safety of your variable localDocumentData, consider defining a specific interface for it.

It seems like the interface should be structured as follows:

interface DocumentData{
  files:File[];
}

interface File{
  file_name:string;
  file_size:number;
}

localDocumentData:DocumentData;

Answer №2

In cases where defining a type is not feasible, the $any placeholder can be utilized:

<div class="item" *ngFor="let item of $any(data).items; index as i;">
      <div class="box">
           <img src={{item.image}} alt={{item.name}}>
           <p>{{item.name}}</p>
           <p>{{ item.price | currency }}</p>
      </div>
 </div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error message: Unable to locate module without the '.js' extension at the end of the import file path

It seems like the solution is not difficult, just something obvious. I am working on a simple TypeScript project. There are no modules involved, only TypeScript for compilation. The TS files compile into JS files in the dist folder, which are then connect ...

Verify if the date surpasses the current date and time of 17:30

Given a date and time parameters, I am interested in determining whether that date/time is greater than the current date at 17:30. I am hoping to achieve this using moment js. Do you think it's possible? This is what I have been attempting: let ref ...

What is the best way to conceal the header and search component in a different component by utilizing navigation?

Current Situation: I am currently dealing with two components (app-header and app-search) that are both included in app.component.html as follows: <app-header></app-header><app-search></app-search> Additionally, I have set up navi ...

Integrating Angular 2 with Java functionalities and JSP

Starting my journey with the Angular 2 framework, I recently dove into working with it. As I delved deeper, many questions began to surface. My initial step was creating an Angular project using the Angular CLI, which went smoothly. However, when I attem ...

invoking a function in one component from another component within an Angular 4 project using ng-smarttable

Utilizing ng-smarttable to display data in a table and have successfully added a custom button in a separate component. However, I am encountering an issue where the data does not reload when clicking on the button. An error message is appearing: ERROR Ty ...

Refused to run script from inline content on the lightweight server due to security policy restrictions

I have been adhering to Angular's best practices in order to create a Progressive Web App (PWA). After building the production version (ng build --prod --aot), I am running it from the dist folder on localhost using npm run dev ("dev": "lite-server"). ...

The Validators.pattern in Angular fails to match when comparing two different versions

I encountered a unique scenario where I need to validate either a datetime format or an empty string. Both should be accepted inputs, but any malformed or incomplete datetimes should fail validation. myForm = this.form.group({ ... ts: [&apos ...

Pull in class definitions from the index.js file within the node_modules directory

In my project, I have the package called "diagram-js" in the node_modules. The file node_modules/diagram-js/lib/model/index.js contains multiple class definitions as shown below: /** * @namespace djs.model */ /** * @memberOf djs.model */ /** * The b ...

Limiting the number of items shown in the dropdown panel of an NgSelect

Currently, I am utilizing Angular ngselect to showcase a dropdown menu with multiple options. However, due to the limited screen space, I need to restrict the number of items visible in the dropdown to about 3, allowing users to scroll through the rest. W ...

How to minimize scaffolding with Redux, React, and Typescript?

Is there a way to avoid the process of instrumenting my Redux-Aware components? The level of scaffolding required seems excessive. Take, for instance, the minimal code necessary to define a redux-aware component: class _MyActualComponent extends React.Co ...

When an additional data stream is introduced, Resolver is unable to effectively resolve the issue

I have been working on implementing a resolver to fetch data based on the parameters provided by the route. However, I encountered an issue where the resolver does not resolve when there is an additional data stream that my data depends on. When I direct ...

In fact, retrieve the file from an S3 bucket and save it to your local

I've been attempting to retrieve an s3 file from my bucket using this function: async Export() { const myKey = '...key...' const mySecret = '...secret...' AWS.config.update( { accessKeyId: myKey, secretAcces ...

Encountering a problem while attempting to compile an Angular 8 application using the "ng build" command

Error Log Below: An error occurs while the application is running with ng-serve, but ng build throws a different error. Generating ES5 bundles for differential loading... Browserslist: caniuse-lite is outdated. Please run the following command npm u ...

Issue with closing the active modal in Angular TypeScript

Can you help me fix the issue with closing the modal window? I have written a function, but the button does not respond when clicked. Close Button: <button type="submit" (click)="activeModal.close()" ...

Angular 2 validation issue not functioning as anticipated

Here is a validator function that I have: export const PasswordsEqualValidator = (): ValidatorFn => { return (group: FormGroup): Observable<{[key: string]: boolean}> => { const passwordCtrl: FormControl = <FormControl>group.contr ...

Setting up AngularJS 1.5.x to function seamlessly with SystemJS and TypeScript

I'm looking to keep all my code in AngularJS 1.x while also preparing it for an easy upgrade to AngularJS 2 in the future. To align my code with Angular 2 standards, I am interested in using TypeScript and SystemJS in version 1.5.x initially. Is ther ...

What is the best way to iterate over JSON data from an endpoint that contains multiple nested arrays using the .map() method?

Seeking to showcase weather API data from: () import Image from "next/image" interface Hour { time_epoch: number time: string temp_c: number temp_f: number is_day: number wind_mph: number wind_kph: number wind_deg ...

"Troubleshooting Angular 2 Directives That Cause Errors

Hey there, I'm currently working on understanding ANGULAR 2 routing, but I've encountered an error that's causing some trouble. Here's the issue I'm facing: app/app.component.ts(7,12): error TS2345: Argument of type '{ s ...

How can I handle returning different types of Observables in my Angular application?

I can't seem to get an observable to return properly. The mergeMap function inside my code doesn't appear to be executing at all. Here are the relevant snippets of code: book.service.ts import {HttpClient, HttpHeaders} from '@angular/comm ...

Is it possible to utilize @ViewChild() or a similar method with a router-outlet? If yes, how can it be

There is a recurring situation I encounter where I find myself wanting to access a child component located on the opposite end of a router outlet instead of through a selector: For example: <router-outlet></router-outlet> NOT: <selector-na ...