Is indexOf the answer to Optional Chaining?

Looking to simplify this code:

function checkIfExist(container?: string[]): boolean {
  if (container) {
    return container.indexOf("element") > -1
  }

  return false
}

...and I had the idea of using Optional Chaining for this purpose. However, it seems to not be working and there might be a misunderstanding on my end...

function checkIfExist(container?: string[]): boolean {
  return container?.indexOf("element") > -1 // ERROR: Object is possibly 'undefined'. (2532)
}

Answer №1

To avoid the undefined object error, consider setting a default value for the parameter haystack as an empty array in your function:

function checkExistence(haystack: string[] = []): boolean {
  return haystack.indexOf("needle") > -1;
}

An even better approach is to use the includes() method instead of .indexOf():

function checkExistence(haystack: string[] = []): boolean {
  return haystack.includes("needle");
}

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

Issue encountered while generating a fresh migration in TypeORM with NestJs utilizing Typescript

I am currently working on a Node application using TypeScript and I am attempting to create a new migration following the instructions provided by TypeORM. Initially, I installed the CLI, configured my connection options as outlined here. However, when I ...

Angular Route Check with If Statement

Can someone assist me with creating an if-statement in my program to determine the current route or path I'm on? I have a function that should only execute when I'm on a specific path. For instance, if the path is "homepage", then I know I' ...

Utilizing ngFor to iterate over items within an Observable array serving as unique identifiers

Just starting out with Angular and I'm really impressed with its power so far. I'm using the angularfire2 library to fetch two separate lists from firebase (*.ts): this.list1= this.db.list("list1").valueChanges(); this.list2= this.db.list("list2 ...

Creating an enum using keys from objects within an array in TypeScript

How can I type a string to be within one of the static IDs in a hardcoded array called storage using const storage : Readonly<{id: string}[]>? The array will remain unchanged during runtime. I attempted (typeof storage)[number]['id'] but i ...

Creating a TypeScript type that extracts specific properties from another type by utilizing an array of keys

In my TypeScript journey, I am working on crafting a type that can transform a tuple of keys from a given type into a new type with only those specific properties. After playing around with the code snippet below, this is what I've come up with: type ...

How is it that the setTimeout of 1 is running before the setTimeout of 0?

setTimeout(() => console.log('1'), 1); setTimeout(() => console.log('4'), 0); setTimeout(() => console.log('3'), 2); setTimeout(() => console.log('2'), 0); The expected output sequence was 4, 2, 1, 3. ...

utilizing routerLinks to transfer data and trigger a specific function

I'm having trouble passing data through the routerLink and calling the function(). It doesn't seem to be working as expected. Here's an example of my code and you can view a working demo on StackBlitz. First Component(HTML) <span [route ...

Using Typescript in the browser with Babel and Webpack: Step-by-Step Guide

I've been exploring the use of Typescript in my browser with a specific architecture: Typescript in browser architecture However, I'm facing an issue with the import/export functionality when running this command: tsc && babel build-ts -d lib && ...

Angular 2: Patience is a Virtue When Dealing with Observables

Dealing with multiple asynchronous calls can be tricky, especially when you need to wait for all of them to finish before moving on to the next step. In my case, I have separate calls that may or may not be made depending on user input. How can I efficient ...

Leveraging AnimatePresence from the Framer Motion library to design an exit animation for a motion.div

My goal is to implement a side menu that smoothly slides in and out when the menu/close button is clicked using framer motion. Initially, clicking on the menu button will cause the menu to slide out from the left side of the screen while changing the butto ...

Angular 2 does not update the variable value within a dataservice call on the page until you navigate away from the page and then come back to it

Currently, I am working with Angular2 and have encountered a strange issue. I have a variable that I display on the page, and when a button is clicked, a data service is called to update the value of this variable. Surprisingly, even after changing the val ...

Utilize generic types within methods in TypeScript

Here is a snippet of code I'm working on in TypeScript: public static sortByProperty<T>( array: T[], prop: string ): void { var availProps: string[] = Object.getOwnPropertyNames( T ); // or something typeof T, anyway I got error i ...

Encountering a hiccup while trying to install Svelte, Skeleton, and Tail

Recently entering the world of Svelte and TypeScript, I have encountered some unexpected errors after installation. Despite following the same steps as before, I am puzzled by what is causing these issues. This is the process I followed: npm create svelte ...

Having trouble invoking an Angular 6 Service using an HTML EventListener

Within my angular ag-grid setup, I've implemented a cellRenderer and cellRendererParams. The cellRenderer calls a method to generate a button in each cell of the ag-grid. constructor(private notificationService: NotificationService) { } ngOnInit() { ...

Can decorators be dynamically added in TypeScript?

As I work on my personal project in NestJS for educational purposes, integrating Swagger has become a key focus. I want to showcase that a specific route could potentially result in an UnauthorizedException response. To achieve this, I need to add the foll ...

The visibility of the button is dependent on refreshing the page with the F5

I'm currently experiencing an issue with my code. The backoffice button is not showing up when I log in as an admin, unless I refresh the page by pressing F5. useEffect(() => { // Ensure window.FB and window.FB.XFBML are defined before calling ...

Getting started with setting up and configuring the matrix-js-sdk

Currently, I am facing challenges while attempting to establish a connection with a matrix server using the matrix-js-sdk within a react application. Below is a simple code snippet that I have provided, ensuring that the credentials are valid (successfull ...

What is the method for throwing errors with NestJS guards without relying on an authentication module?

Are you looking to customize error responses in NestJS guards? import { CanActivate, Injectable, ExecutionContext, NotFoundException } from '@nestjs/common'; import { Observable } from 'rxjs'; import { InjectModel } from '@nestjs/m ...

"Facing an issue where ts-node is not recognizing d.ts files, despite tsc being able to compile them

I am currently using typescript along with express and attempting to enhance the request object in express. Below is my server.ts file: import express, { Request, Response } from "express"; const app = express(); app.use(function(req: Request, res: Respo ...

Implementing global variable sharing across components in Vue 3 using TypeScript while maintaining scope cleanliness: types, classes, and helper functions

Background I am currently developing a Vue application using the Composition API in TypeScript, encountering an issue that I have been unable to resolve. Despite my efforts, I am struggling to articulate the problem or find a solution. (For reference, I a ...