Using Typescript to define classes without a constructor function

As I was going through the "Tour of Heroes" guide on the Angular website, I came across the following code snippet:

class Hero {
  id: number,
  name: string,
}

const aHero: Hero = {
  id: 1,
  name: 'Superman'
}

console.log(aHero instanceof Hero); //false

I couldn't help but wonder about the purpose of this. When I examine the type of "aHero", it appears to be just a regular object and not of type "Hero". Shouldn't we simply initialize objects using a constructor as below?:

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

Answer №1

When it comes to using class as a type, the distinction between whether something is an interface or a class becomes irrelevant. In the example provided, whether Hero is defined as an interface or a class, it serves as a type for the variable.

class Hero { id: number; name: string }

Alternatively, it can be declared as:

interface Hero { id: number; name: string }

The crucial point is that whether Hero is a class or an interface doesn't impact its usage as a type:

let hero: Hero = { id: 1, name: 'me' }

The key difference between an interface and a class lies in the fact that an interface is merely for development purposes and doesn't get converted into JavaScript. On the other hand, a class does get transpiled, and you are unable to create a new instance of an interface.

Whether there is a constructor present or not, if you use new to create an object instance, it will be considered an instanceof that class. This can be demonstrated by:

let hero = new Hero();

Executing a log of instanceof will return true because you have successfully instantiated an object of the Hero class using the keyword new.

Answer №2

While this question may have been addressed previously, when it comes to object-oriented code, the approach has typically been as follows:

It is possible to achieve the desired outcome without utilizing a constructor:

let hero: Hero = { ID: 1, Name: 'goku'};

However, if you prefer to utilize a constructor, you can implement it within the class like so:

class Hero
{
    // Utilizing optional parameters provides greater flexibility.
    constructor(id?: number, name?: string)
    {  
      this.ID = id;
      this.Name = name;
    }

    ID: number;
    Name: string
}

Furthermore, you can then instantiate the object using the following approach:

let hero: Hero = new Hero(1,'goku');
let hero2: Hero = { ID: 2, Name: 'superman' }

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

TypeScript - Minimize redundancy when defining types for a class and its constructor arguments

Here is a class structure I am currently using: class Person { id?: string = uuid(); name: string; constructor(data: Person) { _.merge(this, data); } } The 'uuid' function generates an id and '_' refers to loda ...

The current layout of the div is hindering the ability to switch from vertical scrolling to horizontal scrolling

I'm currently utilizing this scroll converter tool to transform vertical scrolling into horizontal scrolling. However, despite correct script inclusion and initialization, the conversion is not working as expected. It seems like there might be an issu ...

"Incorporating splice in a for loop is causing issues and not functioning

I've been attempting to remove an item from an array, but for some reason, it's not working. Here's the code I'm using: vm.Continue = function () { $scope.invalidList = []; if (vm.errorexsist === true) { var table = doc ...

The creation of the Angular project was unsuccessful due to the outdated circular-json dependency

After attempting to create a new Angular project with the command: ng new hello-world I encountered an error message: npm WARN deprecated <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d6dcc7d6c0d9d4c798dfc6dadbf5859b809b8 ...

Issue with the positioning of the datepicker is not functioning properly

I'm currently facing an issue with the position of a date picker plugin from jquery. The search box on my website allows users to select a range of dates using the date picker, but when enabled, the date picker appears at the bottom left corner of the ...

Scrollable container with jQuery draggable functionality

I am currently working on implementing a draggable list that I want to contain within a scrollable div. $( ".draggable" ).draggable(); Here is the fiddle I have created for this: http://jsfiddle.net/YvJhE/660/ However, the issue I am facing is that the ...

Creating nested Angular form groups is essential for organizing form fields in a hierarchical structure that reflects

Imagine having the following structure for a formGroup: userGroup = { name, surname, address: { firstLine, secondLine } } This leads to creating HTML code similar to this: <form [formGroup]="userGroup"> <input formCon ...

How can one efficiently update numerous data properties in a Vue.js application?

My information is as follows: data() { return { monday_start: '', monday_end: '', tuesday_start: '', tuesday_end: '', wednesday_start: '', ...

Tips on using b-table attributes thClass, tdClass, or class

<template> <b-table striped hover :fields="fields" :items="list" class="table" > </template> <style lang="scss" scoped> .table >>> .bTableThStyle { max-width: 12rem; text-overflow: ellipsis; } < ...

Should the index.js file in Next.js serve as the homepage or solely as the initial starting point?

Should I integrate my homepage directly into the index.js file, or create a separate "home-page.js" file in the pages directory? Is index.js just for initializing the application, or can it serve as a standalone page? Alternatively, should I have index.j ...

Adjust the location.hash and then navigate using the Back button - Internet Explorer displays unique behavior compared to other web browsers

When updating `location.hash`, all browsers behave correctly by only changing the URL without refreshing the page. However, pressing the Back button in Internet Explorer and other browsers results in different behaviors. IE fails to update the history wit ...

What is the way to obtain loading start/end events while using a loader widget in conjunction with an asynchronous Firebase request (observable)?

I have implemented AngularFire in the following manner: constructor(private afDb: AngularFireDatabase) { allRRs$ = this.afDb.list(`research_reports-published/`).valueChanges(); } The variable allRRs$ is an observable that I am utilizing in my templat ...

What methods are available for managing model fields within a for loop in Django?

As a newcomer to Django, I am embarking on the journey of creating a Quiz web application that presents one question at a time. Upon selecting an answer using radio buttons, the application should promptly display whether the response is correct or incorre ...

Obtain the registration ID for Android to enable push notifications by utilizing PushSharp

I am currently utilizing the PushSharp library and have come across deviceToken in the sample code provided on this link. Could someone kindly assist me on how to obtain this deviceToken? The PushSharp sample code does not clearly explain this. apnsBrok ...

An error was detected in the card-module.d.ts file located in the node_modules folder within the @angular/material/card/typings directory

Currently, I am working on an angular project using Visual Studio Code as my text editor. When attempting to open the project with 'npm start', an error occurred. The specific error message is: ERROR in node_modules/@angular/material/card/typing ...

When incorporating an array as a type in Typescript, leverage the keyof keyword for improved

I am facing a situation where I have multiple interfaces. These are: interface ColDef<Entity, Field extends keyof Entity> { field: Field; valueGetter(value: Entity[Field], entity: Entity): any } interface Options<Entity> { colDefs ...

Is it acceptable for a video to autoplay even if it is not connected to the DOM?

Consider the following three scenarios: document.adoptNode, document.importNode, and document.createElement with assigned properties. In all cases, the video autoplay feature is activated even when it's not connected to the DOM. This behavior diffe ...

Guide to merging two endpoints in express.js to create a single endpoint

I currently have 2 existing endpoints named /balance and /transactions. What is the most effective approach to create a new endpoint called /balance-and-transactions without having to refactor the existing code? For example: a('/balance', () =&g ...

What is the best way to eliminate specific duplicate characters from a string using JavaScript?

I have a project involving managing email responses, where the reply function includes pre-written content like Re: ${Subject of the email} The issue I'm facing is that after the 2nd reply, there is a repeated Re: , so I created a function to remove ...

What is the best method to display and conceal a table row in Angular 6?

In the midst of developing a table with multiple rows, I am seeking a way to invisibilize a particular row and then reveal it again using a reset button. Any tips on how to accomplish this task?emphasis added ...