Ways to remedy the "object may be null" issue in TypeScript without turning off strictNullChecks

Below is my typescript code snippet:

const form  = document.querySelector('form');


if (form != null ) {
    const data = new FormData(form);
    for (const pair of data) {
        console.log(pair);
    }
    // OR
    for (const pair of data.entries()) {
        console.log(pair);
    }
}

document.getElementById("form_file")!.onchange= function(e: Event) {
    let file = (<HTMLInputElement>e.target).files[0];
    }

I have attempted the following:

let file = (<HTMLInputElement>e?.target)?.files[0];

and

let file = (<HTMLInputElement>e!.target)!.files[0];

Is there a way to make it work without having to use the strictNullChecks option in tsconfig?

Best regards

Answer №1

The issue lies with the files array and not the e.target HTMLInputElement. To solve this, you need to ensure that the files array is not null or undefined before trying to access the first index.

You can achieve this in two ways:

// The "?.[0]" will only access index 0 if `files` is not null or undefined
document.getElementById("form_file")!.onchange= function(e: Event) {
    let file = (e.target as HTMLInputElement).files?.[0];
}

Alternatively, you can do it like this:

document.getElementById("form_file")!.onchange= function(e: Event) {
    let file;

    if((e.target as HTMLInputElement).files){
        file = (e.target as HTMLInputElement).files;
    }
}

Answer №2

One possible solution to prevent null issues is by properly checking for the existence of elements before accessing them in your code. For example, make sure that the file element and its target files exist before trying to use them.

const input = document.getElementById("form_file");

if (input) {
  input.onChange = function(e: Event) {
    if (e.target && e.target.files) {
      let selectedFile = e.target.files;
    }
  }
}

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

Using the OR operator in Angular's *ngIf directive within a component's HTML

Need help with an *ngIf statement using OR in Angular, but the second condition is not working as expected. See below for the code: <div *ngIf="router.url != '/one' || router.url != '/two'"> show something </div> Any su ...

Tips for efficiently sorting a string array in JavaScript

Looking to sort an array in a specific numerical order? Check out this example: const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'] If you're running into issues when ...

Utilizing Protractor's advanced filtering techniques to pinpoint the desired row

I am trying to filter out the specific row that contains particular text within its cells. This is my existing code: private selectTargetLicense(licenseName: string) { return new Promise((resolve => { element.all(by.tagName('clr-dg-tab ...

Encountering an error message in Angular stating "Spotify is not defined" while utilizing "@types/spotify-web-playback-sdk"

I'm currently integrating Spotify's web player SDK into an Angular project. I followed the steps outlined in this particular question and answer: Installing the types package, then including the types reference at the beginning of the file where ...

Tips for Handwriting combineReducer using Typescript?

Learning redux with typescript has been quite a journey for me. I've successfully implemented combineReducers in my code: export const reducerBase= combineReducers({ stateA: reducerA, stateB: reducerB, stateC: reducerC }); Everything was going ...

What is the process of playing blob videos (avi, mov) in Angular14?

I've been struggling with this issue for quite some time without knowing how to resolve it. After some research, I came across a similar question: how to play blob video in angular. However, the problem is that the demo provided in the answer does no ...

Exploring TypeScript <T that belongs to any array>

getLength function appears to be functional Upon inspection, these two functions seem quite similar (The second one may be more versatile as it can handle objects with properties other than just arrays): During runtime, both functions essentially transla ...

Error message encountered when trying to associate "can" with an ability instance within Types

Just copying example code from documentation import { createCanBoundTo } from '@casl/react'; import ability from './abilities'; export const Can = createCanBoundTo(ability); An error occurs on the last line: The exported variable & ...

`A bug in my Angular 4 application causes a TypeError when hosted on IIS`

After hosting an Angular 4 app on IIS, it seems there is an issue when accessing the app from machines other than the ones used for development. An error message " 'Uncaught TypeError: undefined is not a function' common.es5.js:3084" appears on t ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Warning: The parameter type in the Node JS project is not compatible with the argument type

Upon running this code in WebStorm, I encountered a warning: Argument type {where: {email: userData.emil}} is not assignable to parameter type NonNullFindOptions<Model["_attributes"]> Can someone explain this warning to me? This project ...

Overriding TypeScript types generated from the GraphQL schema

Currently, I am utilizing the graphql-code-generator to automatically generate TypeScript types from my GraphQL schema. Within GraphQL, it is possible to define custom scalar types that result in specific type mappings, as seen below in the following code ...

Iterating over a JSON array using *ngFor

Here is the JSON structure that I have: { "first_name": "Peter", "surname": "Parker", "adresses": { "adress": [{ "info1": "intern", "info2": "bla1" }, { "info1": "extern", "info2": "bla2" }, { "info1": " ...

Querying data conditionally with Angular rxjs

I have a json file that contains multiple arrays structured like this: { A[] B[] C[] ... } This is the query I am using: myFunction():void{ this.apiService.getData() .pipe( map((response: any) => response.A), // to access to the &ap ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am ...

Having trouble with Angular 17 router.navigate not functioning properly?

I'm facing an issue with my angular application where I have two pages - one with a form and the other with data. Upon clicking a button, I navigate to the results page using router.navigate. However, I've noticed that sometimes the navigation do ...

Strategies for resolving type issues in NextJs with Typescript

In my project using Next.js with TypeScript, I encountered an issue while trying to utilize the skipLibCheck = false property for enhanced checking. This additional check caused the build process to break, resulting in the following error: Error info - U ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Encountering an error in Angular where the property does not exist in type

Struggling to create a collapsible menu within my header component in an Angular project, I've hit a snag with proper JSON formatting. The error message that keeps popping up reads: Error: src/app/components/header/header.component.html:48:49 - error ...

Testing in Jasmine: Verifying if ngModelChange triggers the function or not

While running unit tests for my Angular app, I encountered an issue with spying on a function that is called upon ngModelChange. I am testing the logic inside this function but my test fails to spy on whether it has been called or not! component.spec.js ...