Attempting to implement a typeguard in Typescript that relies on the presence of specific content within an element

Currently, I am attempting to develop a Typescript conditional that verifies if a particular word is already present in the name.

The function in question is as follows:


isOrganic() {
    for (let i = 0; i < this.items.length; i++) {
      if(this.items[i].organic) {
        if (' (Organic)' in this.items){
          this.items[i].name = this.items[i].name
        } else {
          this.items[i].name = this.items[i].name.concat(' (Organic)')
        }
      }
    }
  }

The main goal here is to determine whether the ' (Organic)' label is already part of the name. If it is, the name should be used as is. However, if it's missing, it needs to be added. Unfortunately, instead of achieving this result, the label keeps getting appended repeatedly. For instance:

Apple (Organic) (Organic) (Organic) etc...

I'm aware that the issue lies within this specific line: if (' (Organic)' in this.items)

Despite identifying the problem, I'm struggling to devise an appropriate solution through setting up the conditional statement correctly.

Answer №1

Here is a solution for your problem:

if (this.items[i].name.endsWith(' (Organic)'))

To achieve the desired outcome, make sure to access the item's name property fully. Then, utilize string methods like contains or endsWith, as the in operator does not operate directly on strings.

Complete example:

class Foo {
  constructor() {
    this.items = []
  }

  isOrganic() {
    for (let i = 0; i < this.items.length; i++) {
      if (this.items[i].organic) {
        if (this.items[i].name.endsWith(' (Organic)')){
          this.items[i].name = this.items[i].name
        } else {
          this.items[i].name = this.items[i].name.concat(' (Organic)')
        }
      }
    }
  }
}

const foo = new Foo()

// test data
foo.items = [ 
  { name: "A", organic: false },
  { name: "B", organic: true },
  { name: "C (Organic)", organic: true },
]

foo.isOrganic()
console.log(foo.items)


Furthermore, it is important to note that this code can be refactored for better clarity.

  1. Utilize a for/of loop to iterate over the array of items to avoid repetitive calls to this.items[i].
  2. Implement a single if statement that handles cases where the item is organic but lacks the specific text suffix.

class Foo {
  constructor() {
    this.items = []
  }

  isOrganic() {
    for (let item of this.items) {
      if (item.organic && !item.name.endsWith(' (Organic)')) {
        item.name = `${item.name} (Organic)`
      }
    }
  }
}

const foo = new Foo()

// test data
foo.items = [ 
  { name: "A", organic: false },
  { name: "B", organic: true },
  { name: "C (Organic)", organic: true },
]

foo.isOrganic()
console.log(foo.items)

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

Incorporate service providers into models with Ionic3/Angular4

I am seeking feedback from individuals with more experience than me to determine if my approach is correct. I am currently working on an Ionic3-Angular app that involves a CRUD functionality for "Clientes". From what I have researched, the recommended st ...

An example in Typescript for setting an initial/default value for a data type

Can you create a Type with a default value included? For example: type Animal = { kind : "animal" Legs : number, CanFly: boolean } const monkey: Animal = { Legs: 4, CanFly: false}; //In this line, clients must initialize the same value `kin ...

The variable 'BlogPost' has already been declared within the block scope and cannot be redeclared

When working with Typescript and NextJS, I encountered the following Typescript errors in both my api.tsx and blogPost.tsx files: Error: Cannot redeclare block-scoped variable 'BlogPost'.ts(2451) api.tsx(3,7): 'BlogPost' was also dec ...

There is no imageURL property available for this type

Everything was running smoothly on my local project, but encountered errors upon deploying to Vercel: The properties imageURL and alt do not exist on type {} Despite attempting to define the types based on suggestions from Stack Overflow, the issues per ...

Creating and managing global context with useReducer in TypeScript and React

One issue that I am facing is with the route containing a login and logout button, where the browser error states 'Property 'dispatch' does not exist on type '{}'. (home.tsx) import React, { useContext, useEffect, useRef, use ...

Learn how to open a component in a new browser tab using Angular from a different component

I wish to display the MapComponent in a new browser tab when a button in my AppComponent html file is clicked. Currently, when I click the button, the MapComponent opens in a new tab but it also displays the button. How can I configure it so that only the ...

Tips for adjusting the material ui Popper width to fit the container without disabling the portal

Currently utilizing the material-ui popper library. I am trying to allow the popper to extend outside of its container in the vertical direction. To achieve this, I have set disableportal={false}. However, upon setting disableportal to false, when assign ...

Using capital letters with interpolated language keys

The issue: I'm currently facing a problem with i18next. It allows variable interpolation in strings, like "AddNew": "Add new {{item}}". However, I have a language where the grammar requires "{{item}}" to be the first word, as in "AddNew": "{{item}} t ...

How to import a module from the root path using TypeScript in IntelliJ IDEA

Despite this topic being widely discussed, I still struggle to understand it. Below is my tsconfig.json file: { "compilerOptions": { "module": "commonjs", "target": "es2017", "sourceMap": true, "declaration": true, "allowSyntheticDe ...

Errors caused by Typescript transpilation only manifest on the production server

During the process of updating my node version and dependencies on both machines, I came across an issue where building my app in production on one machine resulted in an error, while building it on my main machine did not. I found that the errors disappe ...

The @angular/fire package is unable to locate the AngularFireModule and AngularFireDatabaseModule modules

I am facing some challenges while trying to integrate Firebase Realtime Database into my Angular project. Specifically, I am encountering difficulties at the initial step of importing AngularFireModule and AngularFireDatabaseModule. To be more specific, I ...

Establish HTTP headers for accessing the Oxford API in an Angular 6 application

public performAutocomplete(wordInput):any { let headersOptions = { headers:{ 'Accept': 'application/json', 'app_id': 'myid', "app_key": "mykey" } as any } this.wordTyped = wordInp ...

Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example: // fact ...

Unpacking objects in Typescript

I am facing an issue with the following code. I'm not sure what is causing the error or how to fix it. The specific error message is: Type 'CookieSessionObject | null | undefined' is not assignable to type '{ token: string; refreshToken ...

Navigating the interface types between Angular, Firebase, and Typescript can be tricky, especially when working with the `firebase.firestore.FieldValue`

I am working on an interface that utilizes Firestore timestamps for date settings. export interface Album{ album_name: string, album_date: firebase.firestore.FieldValue; } Adding a new item functions perfectly: this.album ...

Ways to eliminate unnecessary items from a JavaScript object array and generate a fresh array

My JavaScript object array contains the following attributes: [ { active: true conditionText: "Really try not to die. We cannot afford to lose people" conditionType: "CONDITION" id: 12 identifier: "A1" ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Looking to create universal React component wrappers?

I am working with a set of functional components that share a common set of properties, for example: const A = ({ x, y, z }) = {...} const B = ({ x, y, z }) = {...} For these components, I have predefined configurations: const styles { A: { ty ...

Providing the correct context to the function in Angular's dialog data is crucial for seamless

Currently, I have a scenario where a service and a component are involved. In the service, there is an attempt to open a dialog in which a reference to a method existing in the service is passed. The code snippet below provides an example: export class So ...

Create a full type by combining intersecting types

I have multiple complex types that are composed of various intersecting types. I am looking to extract these types into their final compiled form, as it would be useful for determining the best way to refactor them. For example, consider the following: ty ...