Using TypeScript, let's take a closer look at an example of Angular

I am trying to replicate the chips example found at this link (https://material.angularjs.org/latest/#/demo/material.components.chips) using TypeScript. I have just started learning TypeScript this week and I am having some difficulties translating this code from JavaScript to TypeScript:

JS:

function mockLabels() {
      var labels = [
        {
          'name': 'hotel',
          'id': '1'
        },
        {
          'name': 'sport',
          'id': '2'
        },
        {
          'name': 'gaming',
          'id': '3'
        }           
      ];
      return labels.map(function (lab) {
        lab._lowername = lab.name.toLowerCase();
        return lab;
      });
    }

TypeScript:

private mockLabels: Array<Label> = [
            new Label(1, 'hotel'),
            new Label(2, 'sport'),
            new Label(3, 'gaming')
        ];

public getLabels() {
            return this.mockLabels;         
        }

I am struggling to incorporate .map into my TypeScript code after assigning it to an array in TypeScript.

How can I modify mockLabels to achieve this?

Answer №1

It's important to remember that TypeScript is essentially JavaScript with type annotations. To adjust the code accordingly, we can simply add type annotations:

function mockLabels() {
  var labels:{
    name: string;
    id: string;
    _lowername?: string;
  }[] = [
    {
      'name': 'hotel',
      'id': '1'
    },
    {
      'name': 'sport',
      'id': '2'
    },
    {
      'name': 'gaming',
      'id': '3'
    }
  ];

  return labels.map(function (lab) {
    lab._lowername = lab.name.toLowerCase();
    return lab;
  });
}

Note: The original code had a variable named veg which was not defined. I modified it to lab based on my assumption of your intention.

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

Organize a collection of items in AngularJS

Consider the following array: var members = [ {name: "john", team: 1}, {name: "kevin", team: 1}, {name: "rob", team: 2}, {name: "matt", team: 2}, {name: "clint", team: 3}, {name: "will", team: 3} ]; I want to create an unordered list for each ...

The JavaScript and CSS properties are not functioning properly with the HTML text field

I came across this CodePen example by dsholmes and made some modifications: Here Furthermore, I have developed my own form on another CodePen pen: Link The issue I'm facing is related to the placeholders/labels not disappearing when typing in text f ...

Utilizing unique layouts for specific views in sails.js and angular.js

I am currently working on a Sails.js + Angular.js project with a single layout. However, I have come across different HTML files that have a completely different layout compared to the one I am using. The layout file I am currently using is the default la ...

Discovering Unconventional Columns Through Sharepoint REST Api Filtration

I am working on recreating SharePoint's front end in my app and want to add columns to my table just like a user would in SP. The challenge I am facing is determining which columns were custom generated by the user rather than standard ones. Although ...

The functionalities of ng-view in AngularJS

I have been struggling to get ng-view working in a basic example application without any luck. Can anyone help me identify where the code is incorrect? Check out this Plunker here <a href="/one">one</a> <a href="/two">two</a> Cou ...

Transferring information from Controller to View seamlessly without altering the Route

Assume I have multiple Controllers, among them a BaseControlelr. I need to run queries and transfer the data to my Index.cshtml, without altering the url since it's a single page application. Typically, I would set up a Route for my Get request and fe ...

`Zooming and scrolling feature within a masked image`

I'm struggling to achieve a scrolling zoom effect similar to the website mentioned below, but I can't seem to get it to fully zoom. Additionally, when I try to zoom in on a clipped shape or text while scrolling, the entire div ends up scrolling ...

Unable to retrieve the user ID from a Discord username using Discord JS

let string = `${args[1]} ${args[2]}` console.log(string) const idofuser = client.users.cache.find((u) => u.username === `${string}`).id I am facing an issue with DiscordJS where it says "cannot read property 'id' of undefined" when trying to ...

Automatically updating client-side values in AngularJS using setInterval()

Implementing a value calculator on the client side using AngularJS. I need to update the main value of the calculator every 5 minutes with setInterval(). This is my AngularJS code: $http({method: 'GET', url: '../assets/sources.json'} ...

Ways to navigate back to the previous ajax request

I am currently working on a script that involves numerous ajax requests. The script is functioning well, and it features dynamic content that changes based on user selections or search inputs. I have been exploring how to manipulate the browser history in ...

"The controller seems to always return an 'undefined' value for the Angular

Within my project, I have implemented ui-view with the following structure: <main class="content"> <div class="inner" ng-controller="OrderPageController"> <div ui-view="main-info"></div> <div ui-view="comment ...

Guide to creating a functional Async API

I am currently facing a challenge while developing an application for my institution. I need to allow users to access database information (currently using firebase) from an external server, so I set up a node.js server to facilitate communication and hand ...

Continuing a Sequelize transaction after a loop

I am facing an issue where the transaction in my chain of code is committing immediately after the first loop instead of continuing to the next query. Here is a snippet of my code: return sm.sequelize.transaction(function (t) { return R ...

Creating dynamic Kafka topic names within a NestJS microservice

Currently in Nestjs, I have integrated Kafka as my message broker and specified the topic name like so: @MessagePattern('topic-name') async getNewRequest(@Payload() message: any): Promise<void> { // my implementation logic } I am curious ...

What is the process for changing the output paper size to A4 in React Native (expo android)?

Using React Native to develop an Android app for billing purposes, I encountered an issue with the output paper size being 216mmX279mm instead of the standard PDF size of 210mmX297mm. Utilizing expo-print and printToFileAsync from expo, I aim to achieve a ...

How can I generate spheres in threejs with varying radii while all passing through the shared point located at coordinates (0,0,200)?

Is there a way to generate spheres in threejs where the radius increases while always passing through a single point at 0,0,200? This would allow the origin of each new sphere to move along the z-axis. Appreciate any help, AriemWebgl ...

I'd like some clarification on the code that dynamically adds routes using Typescript and Node Express. Can someone please

Running my API server with node/typescript and express / express validator, I came across this code that I found really useful for separating route logic: function createCustomRouter(route: Array<CustomRouteEntry>): Router { const customRouter = R ...

Tips for organizing checkboxes in rows horizontally

My question is related to this issue I am trying to arrange my checkboxes in 4 columns horizontally <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta charset="utf-8"> ...

How can I update an image source using JavaScript in a Django project?

Is it possible to dynamically change the image src using onclick without relying on hard paths or Django template tags? I have concerns that this may not be best practice. How can I implement a method to inject/change the ""{% static 'indv_proj&b ...

Failure to register Express Route

I am currently using express and facing some challenges with creating routes using express.Router. Below is my index.js file (npm main file): require('dotenv').config() const express = require('express') const loaders = require('. ...