What is the best way to ensure TypeScript knows there are no null values in this array?

As I transition from JavaScript to TypeScript, I have encountered a situation with filtering null values from an array. In JavaScript, I would typically use .filter(x => x) to achieve this. However, in TypeScript, it is asking me to specify that the array may contain null, even though the intention is to remove all instances of null from the array:

interface ILabels {
    alias: string
    publicKey: string
    lat: number
    long: number
}

const labels: ILabels[] = data.map((d) => {
  if (d.lat && d.long) {
    return {
      alias: d.alias || d.publicKey,
      publicKey: d.publicKey,
      lat: d.lat,
      long: d.long,
    };
  }
  return null;
}).filter((x) => x);

I am wondering how I can communicate to TypeScript that there will not be any null values in this array. The error message thrown by TypeScript reads as follows:

TS2322: Type '({ alias: string; publicKey: string; lat: number; long: number; } | null)[]' is not assignable to type 'ILabels[]'.   Type '{ alias: string; publicKey: string; lat: number; long: number; } | null' is not assignable to type 'ILabels'.     Type 'null' is not assignable to type 'ILabels'.

Answer №1

To ensure non-null values, you can utilize a custom type guard:

function notEmpty<T>(val: T | null): val is T {
  return val !== null;
}

const labels: ILabels[] = data.map((d) => {
  if (d.lat && d.long) {
    return {
      alias: d.alias || d.publicKey,
      publicKey: d.publicKey,
      lat: d.lat,
      long: d.long,
    };
  }
  return null;
}).filter(notEmpty);

Alternatively, you can use an arrow function:

const labels: ILabels[] = data.map((d) => {
  if (d.lat && d.long) {
    return {
      alias: d.alias || d.publicKey,
      publicKey: d.publicKey,
      lat: d.lat,
      long: d.long,
    };
  }
  return null;
}).filter(<T,>(x: T | null): x is T => x !== null);

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

How can I pass a service method as a parameter in an Angular 2 component?

Within the component: myFunction(): void { this.myOtherFunctoin(this._myService.serviceMethod); } private myOtherFunction(func : Function){ func(); } Regarding service calls: serviceMethod(){ this.somethingMethod(); // "this" is coming as ...

Exploring the capabilities of supertest by testing endpoints in Express with NodeJS

Having trouble setting up a test environment to test my TypeScript Express Node.js endpoints. Here are the packages I've installed: jest ts-jest jest-junit supertest @types/supertest @types/jest This is how my spec file looks like: imp ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Deleting and inserting an element in the Document Object Model

I am currently working on developing a framework and need to create a directive called cp-if. Unlike the existing cp-show directive, where I can simply change the visibility of an element to 'none' and then make it visible again, with the cp-if d ...

Getting a JSON response from a JSP page through an AJAX request

I'm encountering an issue with a JSP page that is supposed to send a JSON response when requested through an AJAX call. However, the response is being directed to the error part of the AJAX call instead of the success part. Below is the code in my JS ...

Efficiently sending a cookie with an Axios POST Request

My request is not receiving a cookie even after trying various solutions like withCredentials. I have pasted the most recent code here, can anyone spot what might be missing? var cookie_for_data = "token=test"; var host = "http://localh ...

Styling images and text in CSS within a jQuery UI autocomplete widget

I am currently using an autocomplete widget that displays text along with images. The results I have right now are not meeting my requirements. I want to customize the appearance of my results so that the words 'test' and either 'Federico&a ...

Discovering a value within a dictionary list

Having a list of dictionaries like this: l = [{'campo': 'Admin_state', 'valor': 'enable'}, {'campo': 'LinkState', 'valor': 'enable'}, {'campo': 'ONU_in ...

Dealing with precompile array warning when utilizing a basic router in Angular 2

I am currently working on developing a straightforward router-based application in Angular2 using typescript. The version of Angular2 I am using is 2.0.0-rc.4, and the router version is 3.0.0-beta.1 Here is my Routes configuration- App.routes.ts import ...

Troubleshooting problems in transferring JSON data between a React application and a Spring Boot service running locally

Running a local Springboot server, accessing it locally in the browser returns a properly formatted JSON object. However, encountering issues when trying to fetch this JSON object from a React application running on node locally. Managed to overcome CORs h ...

Locate all elements by a segment of the identification attribute

Is it feasible to achieve the following: I possess a collection of divs, all having IDs that conclude with '_font', such as 'body_font', 'heading_font', 'tagline_font', and so on. Is there a method to retrieve thes ...

How to transmit data using ajax through a hyperlink? (Without relying on ExtJS, jQuery, or any other similar libraries)

I have a link that says "follow me" and I want to send some basic data to the page without having it reload. Update: I just realized that using "onclick" will help me achieve what I need. Got it. Update 2: I mean, something like this: follow me ...

Tips for displaying Vue Components on an HTML5 canvas surface

How can I incorporate an htmlcanvas as the webpage background and overlay Vuejs components on top of it? I know the answer must exist, but I'm not sure where to start looking. ...

Is it possible to check dynamically if a string contains multiple substring matches?

Currently, I am in the process of developing a search suggest feature that will provide the best match based on certain criteria. Below is the code snippet along with my explanatory comments. /* string = {"Canna Terra PLUS 50 Litres", "Canna Vega ...

Exploring the best way to use $set in Mongoose for dynamically updating an embedded

I'm currently attempting to create a unique function that can update the value of a specific embedded MongoDB document within an array. The goal is to change the value based on its position. function removeAddress(accountNum, pos) { const remove ...

Undefined variable when initializing with ng-init

As a newcomer to AngularJS (and JavaScript in general), I'm currently facing an issue that I could use some help with. Below is the HTML template I am using: <ion-view view-title="Playlists"> <ion-content> <ion-list> ...

How can you include a multi-layered array within another multi-layered array using TypeScript?

If we want to extend a two-dimensional array without creating a new one, the following approach can be taken: let array:number[][] = [ [5, 6], ]; We also have two other two-dimensional arrays named a1 and a2: let a1:number[][] = [[1, 2], [3, 4]]; let ...

I'm facing an issue with this error message - DiscordAPIError: Unable to send a message that is empty. How can I

What's the solution to this issue? Error: UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send an empty message Code: let y = process.openStdin() y.addListener('data', res => { let x = res.toString().trim().split(/ +/g) ...

In JavaScript, would you like to loop through a nested object and assign an empty value of "" to each key, and then generate an array of these modified objects?

Basic Element : elem = { "site": "{{basic_siteId}}", "elementDetails": [ { "subElementInfo": "{{basic_elementInfo}}", "category": "other", "picture": "abc.jpg", "attributes": { ...

Decode a JSON string that has already been encoded

Currently, I am dealing with JSON strings in which the quotes are not properly escaped. The strings are structured like this: { "foo" : "hello my name is "michael"" } Is there a practical way in JS/PHP to escape the quotes within the value without manual ...