What purpose does the class serve in typescript?

This is a unique version of app.component.ts in the Angular Tour of Hero tutorial.

import { Component } from '@angular/core';

export class Superhero{
 name : string;
 id : number;
}

const SUPERHEROES : Superhero[] = [
    {name : 'Wonder Woman', id : 1},
    {name : 'Iron Man',id : 2},
    {name : 'Spider-Man',id : 3},
    {name : 'Black Panther',id : 4},
    {name : 'Thor', id : 5}
];

I was intrigued by how classes work in TypeScript, so I examined the app.component.js file and came across the following code:

var Superhero = (function () {
 function Superhero() {
 }
 return Superhero;
}());
exports.Superhero = Superhero;
var SUPERHEROES = [
 { name: 'Wonder Woman', id: 1 },
 { name: 'Iron Man', id: 2 },
 { name: 'Spider-Man', id: 3 },
 { name: 'Black Panther', id: 4 },
 { name: 'Thor', id: 5 }
];

I'm having trouble understanding the connection between the HEROES array and the Superhero class that I created in app.component.ts. It seems like there's no link between them in the app.component.js file.

Answer №1

I am having trouble understanding the purpose of using classes in the app.component.js file, as there seems to be no connection between the HEROES array and the Hero class that I created in the app.component.ts file.

You're absolutely correct. It should indeed be linked. Maybe we shouldn't focus too much on the compiled code for older browsers. Instead, consider compiling for modern JavaScript engines, where the "class" keyword would still exist and your question would remain relevant.

Let's take a look at this piece of code which declares an ES6 class (with some TypeScript syntax):

export class Hero {
  name: string;
  id: number;
}

In order to instantiate this class, you can only do so with the "new" operator:

However, keep in mind that a class can only be invoked using the "new" keyword (source: exploringjs from Dr. Axel Rauschmayer)

The following code may be confusing:

const HEROES : Hero[] = [
  {name : 'John Snow', id : 1},
  {name : 'Wiz Khalifa',id : 2},
  // ...
];

This code declares an array of type "Hero[]", but it doesn't actually execute the constructor. Instead, it fills the array with objects that are not instances of the class.

Possible solutions

Using an interface:

export interface Hero {
  name: string;
  id: number;
}
const HEROES : Hero[] = [
  {name : 'John Snow', id : 1},
  {name : 'Wiz Khalifa', id : 2},
  // ...
];

Or, using a class:

export class Hero {
  constructor (public name: string, public id: number) {
  }
}

const HEROES : Hero[] = [
  new Hero('John Snow', 1),
  new Hero('Wiz Khalifa', 2),
  // ...
];

Answer №2

The purpose of using a Transpiler in this context is to convert the Type script class into javascript 5 or ES5 compatible code. In ES5, instead of using class syntax to define "classes", function syntax is used. Here's an example:

function vehicle() { } //This defines a "class" called vehicle but it doesn't have any functionality yet

//This defines a function of vehicle that returns the maximum speed
vehicle.prototype.maxSpeed = function() {
 return "50 MPH";
}

As you can see, there are no specific types mentioned here as JavaScript is dynamically typed. Declarations aren't necessary until after the class has been declared.

In your given example, the absence of Name and ID is due to them being used for compile-time error checking in TypeScript. These properties wouldn't exist in their transpiled JavaScript classes.

Regarding the constant heroes, they simply represent JavaScript objects that take on the shape of your instantiated class.

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

Error: The function registerUser from require(...) is not defined

I am facing an issue where I am trying to import the registerUser function inside router.post within the same file that houses its exported function (registerUser). However, when attempting to use it outside of this module, I receive the following error: ...

Communication between the Node development server and the Spring Boot application was hindered by a Cross-Origin Request

Here is the breakdown of my current setup: Backend: Utilizing Spring Boot (Java) with an endpoint at :8088 Frontend: Running Vue on a Node development server exposed at :8080 On the frontend, I have reconfigured axios in a file named http-common.js to s ...

Bringing in a variable from a component that is dynamically imported

I have a dynamically imported (Map) component on my page. const Map = dynamic(() => import('../components/Mapcomp'), { ssr: false, }) In addition to the component, I also need to import a variable from it. const [taskImg, setTaskImg] = useS ...

Cannot display value in NumericFormat when using MUI TextField due to prefix restrictions

When using MUI TextField with the NumericFormat and prefix prop, there seems to be an issue. If I start typing a number quickly, only one digit gets registered. On the other hand, if I type slowly all my numbers show up but the prefix disappears. All inp ...

Utilize jQuery to export HTML or JSON data to an Excel spreadsheet

I am looking for a way to export json or html data to an excel sheet using only html and jquery, without involving any server code. I have found some fiddles that allow me to download the excel sheet successfully, but unfortunately, none of them work in In ...

Implementing authorization middleware using Express.js in Ajax

My app has a straightforward authorization middleware that functions flawlessly with regular GET and POST requests. However, when I send a POST request via AJAX, the middleware fails to redirect to a 401 page and instead bypasses it, allowing the data to b ...

What steps should I follow to run my JavaScript application locally on Linux Mint?

Currently, I am diligently following a tutorial and ensuring that each step is completed accurately. My goal is to locally host my javascript app at localhost:3000. Unfortunately, I am facing difficulties as every attempt to run npm run dev results in an e ...

Exploring the functionality of a personalized hook using the useSelector method

I have developed a custom hook and I am in the process of testing it independently. However, I am encountering an issue where I need to wrap the hook inside a Provider to proceed further. The error message I am getting is displayed below: Error: could not ...

What is a Mongoose Schema type in TypeScript and how can it be used as a custom

https://i.stack.imgur.com/mtlRi.png Could anyone assist me with storing a custom object that includes attributes from the StationRating interface? ...

Rendering the page using ReactDOM.render

Just started with ReactJS, I'm struggling to figure out why my page isn't displaying anything - <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> ...

This TypeScript error occurs when the props are not compatible and cannot be assigned to

Hello fellow Internet dwellers! I am a novice in the world of coding and TypeScript, seeking some assistance here. I am attempting to extract an array of objects from props, transform it into a new object with specific information, and then return it - ho ...

JS URL verification: ensuring valid URLs with JavaScript

Is it possible to combine two scripts that perform separate actions, one clicking a button and opening a new window, and the other interacting with elements in that new window simultaneously? function run() { var confirmBtn = document.querySelector(".sele ...

Adding the location of the onClick event to the hook - a step-by-step guide

Here is the code I am working with: import { MapContainer, TileLayer } from "react-leaflet"; import React, { useState } from 'react'; export default function App() { const [positionLat, setPositionLat] = useState(null); ...

unable to retrieve information from the redis cache

Attempting to retrieve data from cache using the readData function in the controller file. Encountering an issue where the someVal variable is initially undefined after calling readData, but eventually gets populated with data after receiving a callback ...

What are the implications of a project containing nested node_modules directories?

We are currently in the process of dividing our project into "sub modules" within a single repository. Our goal is to maintain aspects such as webpack configurations and express server globally, with a structure similar to the following: package.json serv ...

When a specific condition is met, Jquery can automatically execute a function contained

I am trying to slowly reveal the h1 tag using jQuery for demonstration purposes. The scroll function is working when I manually click to initiate it, but I am having trouble triggering it automatically. I feel like I might be missing something simple and ...

When utilizing $resource, Protractor experiences a timeout while trying to synchronize with the page

Currently, I am testing Protractor with a small AngularJS application. Here is the test scenario: describe('Testing Protractor', function() { var draftList; it('should count the number of drafts', function() { browser.get(&ap ...

Navigating Angular.js: finding my way to the endpoint paths

Despite my best efforts and extensive research, I find myself in need of assistance! I have a web application that utilizes node and express on the server side, with Angular on the client side. My issue lies with angular routing. IMPORTANT DETAILS My cur ...

Consolidate all data connected to the specified key from a JSON dataset

Looking at the json string presented below [{"_id":"9/17/2015","amt1":0,"amt2":13276.5},{"_id":"9/18/2015","amt1":8075,"amt2":6445.5}] The expected outcome is: [{"_id": ["9/17/2015", "9/18/2015"], "amt1": [0, 8075], "amt2": [13276.5, 6445.5]}] Is there ...

Is there a way to incorporate additional text into option text without compromising the existing values?

One challenge I'm facing is adding additional text to the options without changing their values upon selection. Would you be able to assist me with resolving this issue? I have come across the following HTML code: <select id="q_c_0_a_0_name"> ...