Where can the body of this function be located in Typescript and do the generics serve a practical purpose?

While perusing the documentation for Angular's "AsyncPipe", I found myself at a standstill on line 26, where the 'resolve' function is invoked: this.resolve !('hi there!');

I have some questions on my mind:

  • (A) Where is the implementation of this function located? After experimenting with different parameters and types such as resolve(1, 'hello', true), resolve(1), or resolve(), I noticed that in every scenario, the value of the FIRST parameter was returned (an empty output in the last case), even though I couldn't find where this function is defined.
  • (B) Line 19 specifies the Promise with <string>, but as seen in (A), I successfully passed and received strings, numbers, booleans... Did I misconstrue the purpose of this typing?

Any insights would be greatly appreciated!

Answer №1

Here are a couple of points to consider:

(A) The resolve function, along with reject, is specific to Promises. These functions are used asynchronously to determine how to handle the result (resolve) or an error (reject). The resolve function only returns the first parameter; if you need to return multiple values, consider using an object.

(B) Typescript is only present in the IDE/code editor, not during runtime. At runtime, Typescript is transpiled into JavaScript, and some features (such as generics) may be lost in the browser. Generics help ensure you don't mistakenly use a Number function on a String, for example. While you can input any type in Angular applications, during development, your IDE should notify you of any type mismatches (especially if you are utilizing tslint with your development tools).

Answer №2

The function this.resolve is set on line 19:

this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; });

The Promise<string> specifies that the variable resolve should only accept a string argument (i.e. resolve: (string) => void).

this.resolve is declared on line 13:

private resolve: Function|null = null;

Since it is defined with type Function|null, there are no restrictions on the number or type of arguments it can be called with.

An exclamation point ! is used when referencing it (as in this.resolve!(...)) because its type includes null, and the ! asserts to the compiler that the value is not null at that particular point.

The provided example code could be improved as follows:

export class AsyncPromisePipeComponent {
  greeting: Promise<string>;
  arrived: boolean = false;

  private resolve: (string) => void;

  constructor() { this.reset(); }

  reset() {
    this.arrived = false;
    this.greeting = new Promise<string>((resolve, reject) => { this.resolve = resolve; });
  }

  clicked() {
    if (this.arrived) {
      this.reset();
    } else {
      this.resolve('hi there!');
      this.arrived = true;
    }
  }
}

The changes made include:

  • Removing the null initialization:
    • No need to initialize with null,
    • Calling this.reset() in the constructor ensures these properties are immediately set, avoiding any chance of being null.
    • Prefer using undefined when necessary.
    • This allows for skipping the ! in this.resolve!().
  • private resolve: (string) => void
    :
    • Being specific when declaring types is encouraged.

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 a function call disrupts the current scope

Encountering a similar issue to the one discussed here: AngularJS directive binding a function with multiple arguments Following the guidance provided in this answer: Condensing the information as much as possible. Here is the working example: <my-d ...

Exploring the Implementation of the DELETE Method in Angular 5

I'm facing an issue with CRUD operations in my Angular 5 application. The GET and POST methods are working fine, but the DELETE method is not removing dynamic data as expected. The error message I'm encountering is: DELETE http://172.16.47.34:8 ...

Dealing with Error TS2769 in Visual Studio Code when passing props to a custom component in Vue 2 with Typescript

I've encountered an issue with a Vue JS component that involves passing a custom prop. I am utilizing the Vue Options API without utilizing the class component syntax. Whenever I pass ANY prop to my custom component the-header, I receive an error sta ...

Enhancing Javascript-written React components with Typescript typings

Looking for guidance on incorporating TypeScript typings into my existing set of React components written in JavaScript and Flow. Unsure about the best approach, so any assistance would be greatly valued. The current project structure is as follows: / | ...

Creating a unique type with a suffix of `px`

Understanding how to create a Position type class is clear: class Position { x: number = 0; y: number = 0; } However, I now require the x and y values to be integers with the suffix of px, like this: const position = { x: '1px', y: &ap ...

Creating PropTypes from TypeScript

Currently in my React project, I am utilizing TypeScript along with PropTypes to ensure type checking and validation of props. It feels redundant to write types for both TypeScript and PropTypes, especially when defining components like ListingsList: inte ...

Tips for infuriating TSC with Lookup categories

I'm looking for the Typescript compiler (TSC) to throw errors when I make mistakes in signatures. export class EventEmitter<EventTypes extends { [key: string]: any }> { subscribe<Event extends keyof EventTypes>(type: keyof EventTypes, ...

What could be causing the Toast message to not show up in react-native-root-toast?

Incorporated react-native-root-toast into my expo project running on expo 51. Please see the code snippet below for reference: const toastColors = { 'error': { color: '#DA5C53', iconName: <WarningIcon size="5 ...

Display text inputted by the user in a paragraph using Angular upon clicking a button

Currently, I am diving into the world of Angular and facing a specific challenge: My goal is to have an input field for text, a button next to it, and then a paragraph tag. What I aim to achieve is to display the text from the input field in the paragraph ...

Modifying state within reducers is not allowed

Encountered the following error while using @ngrx/store: index.js?4b23:19 State mutation is prohibited inside of reducers. (anonymous) @ index.js?4b23:19 (anonymous) @ index.ts:54 rootReducer @ index.ts:70 _initialStateFactory @ ng2.ts?2a33:24 AppModule ...

Fashion for the repetitive elements, activated by events

Looking for ways to style a specific table element that is generated from a repeat.for loop on a <td> tag. <td repeat.for="field of fields" class="${field.fieldKey == 'validTo' ? 'fontweigth: bold;': ''}"> b ...

Angular 5 Directive for Structuring Content

I'm currently in the process of developing a versatile search box component, with the following setup: search.component.html <div class="search-box-container"> <fa-icon class="search-icon" [icon]="faSearch"></fa-icon> <input ...

Observables and the categorization of response data

Understanding Observables can be a bit tricky for me at times, leading to some confusion. Let's say we are subscribing to getData in order to retrieve JSON data asynchronously: this.getData(id) .subscribe(res => { console.log(data.ite ...

angular determine if a column exists within a matCellDef iteration

Is there a way to check a column in an ng for loop in Angular without using the logic "{{element[p.key] != null ? '$' : ''}}" for a specific column or excluding a specific column? View image description here #html code <table mat-t ...

Running "npm start" does not automatically recompile or display code changes

My experience with my Angular project has been smooth until today. Surprisingly, without making any changes, the "npm start" command suddenly stopped working properly. The project compiles successfully, but any subsequent code changes do not trigger an aut ...

React does not allow _id to be used as a unique key

When I retrieve the categories from my allProducts array fetched from the database using redux-toolkit, I filter and then slice the array for pagination before mapping over it. However, I keep encountering a warning: Each child in a list should have a un ...

Displaying only the most recent 5 messages using *ngFor

I'm facing a situation where my *ngFor loops through incoming messages in this structure. <ul id="messages"> <li *ngFor="let message of messages; let i = index"> <span id="actualMessage" [innerHTML] ...

Prevent the array from altering its values

I am utilizing a mock-service that is configured in the following way: import { Article } from "./article"; export const ARTICLES: Article[] = [ new Article( 1, 'used', 5060639120949, 'Monster Energy& ...

Creating a personalized 404 page in your Angular Project and configuring a route for it

I am currently working on an Angular project that includes a component named 'wrongRouteComponent' for a custom 404 page. Whenever a user enters a non pre-defined route, the 'wrong-route.component.html' should be displayed. However, I a ...

The JestImportMeta interface is mistakenly extending the ImportMeta interface, causing an error

While transitioning from jest version 27 to v29, I encountered this issue: node_modules/@jest/environment/build/index.d.ts:329:26 - error TS2430: Interface 'JestImportMeta' improperly extends interface 'ImportMeta'. The types returned ...