Tips for generating a new method using an existing one

Searching for the best practice to inform the ts compiler that a method will be generated at runtime.


interface Todo { /* ... */ }

export class TodoModel {
 todos: Todo[] = [];
 
 constructor() {
//...
 }

 bindTodoListChanged(callback : (todos: Todo[]) => void) {
   this.onTodoListChanged = callback
 }

 _save(todos: Todo[]) {
   this.onTodoListChanged(todos)
   localStorage.setItem('todos', JSON.stringify(todos))
 }

}

An error I encountered:

 Property 'onTodoListChanged' does not exist on type 'TodoModel'. Did you mean 'bindTodoListChanged'?

Thought using an assert ! would fix it

 bindTodoListChanged(callback : (todos: Todo[]) => void) {
   this.onTodoListChanged! = callback
 }

 _commit(todos: Todo[]) {
   this.onTodoListChanged(todos)
   localStorage.setItem('todos', JSON.stringify(todos))
 }

I also attempted


onTodoListChanged(todos: Todo[]): void

 bindTodoListChanged(callback : (todos: Todo[]) => void) {
   this.onTodoListChanged! = callback
 }

 _commit(todos: Todo[]) {
   this.onTodoListChanged(todos)
   localStorage.setItem('todos', JSON.stringify(todos))
 }

Resulting in this error:

Function implementation name must be 'onTodoListChanged'.

Tried

"strictPropertyInitialization": false
in my tsconfig.json But prefer avoiding config alterations.

Answer №1

To resolve the issue, you should define the class field named onTodoListChanged as an optional property since it may not always be present:

class TodoModel {
    /* ⋯ */
    onTodoListChanged?: (todos: Todo[]) => void
    /* ⋯ */
}    

This adjustment will prevent any complaints from the compiler about the absence of onTodoListChanged:

bindTodoListChanged(callback: (todos: Todo[]) => void) {
    this.onTodoListChanged = callback // acceptable
}

Given that it is optional, you need to verify its existence prior to invoking it; one way to achieve this is by utilizing the optional chaining operator (?.):

_save(todos: Todo[]) {
    this.onTodoListChanged?.(todos) // acceptable
    localStorage.setItem('todos', JSON.stringify(todos))
}

Playground link for code reference

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

Tips for evaluating the stickiness of a block within a cell when it adheres to a mat-header-cell

I am working with an Angular table and facing an issue. How can I make the span element in the cells of the first column stick to the sticky mat-header-row when scrolling down the table? My requirement is for the span element to stay attached to the lower ...

How can this be happening? It's expected that items will be printed, but for some reason

I'm struggling to figure out why the console.logs aren't showing up. import { GenericRepository, getGenericRepository } from '../src/database/repository/GenericRepository'; import { start, stop } from '../src/index'; import r ...

Is your Angular5 service failing to transmit data?

I have two components in my code, A and B. Component A contains a form with data that I want to send to component B. However, it seems like component B is not receiving any data. Here is the code for Component A: import { MyService } from 'path/my ...

A step-by-step guide to activating multi-selection in the Primary SideBar of Visual Studio Code using your custom extension

Currently, I'm in the process of developing an extension for Visual Studio Code where I've added a new activityBar containing treeViews that showcase information pulled from a JSON file. My goal is to enable users to multi-select certain displaye ...

Issue with Ionic 4 IOS deeplinks: Instead of opening in the app, they redirect to the browser

After working diligently to establish deeplinks for my Ionic 4 iOS application, I meticulously followed a series of steps to achieve this goal: I uploaded an Apple site association file to the web version of the app, ensuring the utilization of the prec ...

Having trouble triggering a click event with React testing library?

I am working with a <Select/> component as shown in the image below. https://i.sstatic.net/ko8Y0.png App.tsx import React, { useState, ChangeEvent } from "react"; import MySelect from "./MySelect"; export default function App ...

The error message "TextEncoder is not defined with mongodb nodes" is indicating that there is

Encountering an issue while running jest test cases: Getting the error message - ReferenceError: TextEncoder is not defined. Current Node version being used is 14.18.0. Mongodb NPM package version is 4.1.3. Typescript version installed is 4.4.3. Here ...

Updating the default value for react-i18next (stored in localstorage)

When utilizing a backend and language detector, an issue arises: The localstorage contains the key I18nextLng with the value en-US. How can we set the default value to be I18nextLng with the value En? init and other settings are as per the default docume ...

The component is failing to store its value within the database

I'm encountering an problem when attempting to save an option in the database. To address this issue, I created a component in Svelte called StatePicker that is responsible for saving US States. However, when I try to save it in the database using a ...

Schedule - the information list is not visible on the calendar

I am trying to create a timeline that loads all data and events from a datasource. I have been using a dev extreme component for this purpose, but unfortunately, the events are not displaying on the calendar. Can anyone offer any insights into what I might ...

A mistake has occurred: Unhandled promise rejection TypeError: Unable to assign the property 'devices' to an undefined object in Ionic 4 with Angular

Within my MyDevicesPage class, I am attempting to manipulate the res object and then pass it to the updateDevicesToServer method of DataService for further actions. The code compiles without errors, but at runtime, an error is thrown: ERROR Error: Uncaught ...

Is it possible to utilize the inline/hardcoded type declared in the component.d.ts file for reuse

Is there a way to pass props selectively to the library component? The library has hardcoded multiple values in an inline type. If my code needs to automatically update with any new additions to the library-defined type, can I reuse those inline values r ...

AngularJS - Sending event to a specific controller

I am facing an issue with my page where a list of Leads each have specific actions that are represented by forms. These forms can be displayed multiple times on the same page. Each form has its own scope and controller instance. After submitting a form, an ...

What method can I use to reach the controller of a route that has been exported to another route?

I am currently incorporating nested routes in my TypeScript project. I have set up a router named review.route.ts with the following code snippet: > review.route.ts import { createReview } from "@controller..."; const reviewsRouter = Router() as Expre ...

Issue: Angular 14 - Validators Not Resetting in Nested FormGroup

I am currently working on implementing a nested FormGroup. However, I have encountered an error when attempting to reset the form. Here is the structure of the form: form: UntypedFormGroup; this.form = this.fb.nonNullable.group({ f1: [''], f2: ...

Leveraging an external Typescript function within Angular's HTML markup

I have a TypeScript utility class called myUtils.ts in the following format: export class MyUtils { static doSomething(input: string) { // perform some action } } To utilize this method in my component's HTML, I have imported the class into m ...

How to Add a Rule to an Existing Application Load Balancer Listener using AWS CDK

When I inherited a project, I discovered an application load balancer with a HTTPS Listener that was set up before I began using CDK. This listener currently has 13 rules in place that route requests based on hostname to different fargate instances, with ...

Utilizing RxJs Observables in a service across various pages necessitates manual triggering of change detection

I have an observable in a shared service that is being used by multiple pages. The issue arises when the value of the observable is changed on one page and then I navigate to another page, as the subscription on the second page does not detect any change ...

The system encountered a TypeError: Unable to access the 'nativeElement' property as it is undefined

Hello, I am a beginner in Angular 2 and currently working on an image cropping plugin. My goal is to display the image on a canvas element. Below is my HTML code: <div class="row"> <div class="col-sm-6"> <canvas id="layout" width="40 ...

Capture and store the current ionic toggle status in real-time to send to the database

I have a list of names from the database that I need to display. Each name should have a toggle button associated with it, and when toggled, the value should be posted back to the database. How can I achieve this functionality in an Ionic application while ...