Expanding upon TypeScript by inheriting interfaces

My goal is to create a User module with multiple classes such as UserDetail, UserResetPassword, and more.

These classes will have some common properties that need to be shared. One approach is to declare the properties in each class and initialize them individually.

Alternatively, I could use inheritance by declaring an interface:

export interface IUser {
    UserID: string;
    UserName: string;
}

Then implement this interface in the classes:

import {IUser} from './IUserDetail'

class UserInfo implements IUser {}

My question is: is this supported in TypeScript? If not, what are some workarounds to resolve this?

Answer №1

TypeScript introduces a concept known as "type erasure," where all type information is stripped away during the compilation process. This results in the JavaScript output containing no traces of type annotations, interfaces, or ambient declarations, only the actual code.

As a consequence, when you attempt to access the Iuser interface using your module loader at runtime, it won't be found in the resulting JavaScript file.

To address this issue, it is advisable to place your interfaces alongside their primary implementations in separate files. This approach ensures that you don't encounter errors trying to load a module that turns out to be an empty file.

For instance:

export interface Iuser {
    UserID: string;
    UserName: string;
}

export class UserInfo implements Iuser {
}

In other files, you can then do:

import * as User from './UserInfo';

export class Example implements User.Iuser {
}

Answer №2

Take a look at this example:

After compilation, interfaces do not physically exist but serve the purpose of type checking.

// i-user.ts

export interface IUser {
    UserID:string;
    UserName:string
}

In other programming languages, you must implement all members of an interface. TypeScript ensures that nothing is missed during implementation.

// user-info.ts

import { IUser } from './i-user'

export class UserInfo implements IUser {
    UserID:string;
    UserName:string;
    OtherInfo:string;
}

By using the extend keyword, all methods from the parent class are inherited automatically without needing to re-implement them.

// specific-user-info.ts

import { UserInfo } from './user-info'

class SpecificUserInfo extends UserInfo {
    logInfo() {
        console.log(this.UserID, this.UserName);
    }
}

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 Typescript to Define Mongoose Schemas

Currently exploring the creation of a user schema in TypeScript. I've observed that many people use an interface which functions well until I introduce a message involving username.unique or required property. No error code present: import {model, mo ...

Is there a way to assign a null value to an empty material UI text field when submitting the form, rather than an empty string?

One issue I am facing is that the default value of the text field is zero, but when I submit the form, the value of the text field becomes an empty string instead. This is not the intended behavior as I want the value to remain zero in the end. How can I r ...

Obtain a string of characters from different words

I have been trying to come up with a unique code based on the input provided. Input = "ABC DEF GHI" The generated code would look like, "ADG" (first letter of each word) and if that is taken, then "ABDG" (first two letters o ...

Utilizing Union type and static declarations instead of String Enum

In my opinion, the following approach works better in TypeScript compared to using Enums. I am looking for a way to simplify this process, perhaps by using a utility type. It would be ideal if we could define Enums to function in a similar way, but unfortu ...

Obtaining the value of an ion-toggle in Ionic2 using the ionChange

Below is the toggle I am referring to: <ion-toggle (ionChange)="notify(value)"></ion-toggle> I am looking for a way to retrieve the value of the toggle when it is clicked in order to pass it as a parameter to the notify method. Any suggestion ...

Troubleshooting in Visual Studio Code using an npm script

Within my package.json file, I have defined some scripts as shown below: "scripts": { "build": "tsc -p tsconfig.json", "run": "node --experimental-specifier-resolution=node .", "start" ...

Steering clear of Unfulfilled Promises in TypeScript. The Discrepancy between Void and .catch:

When it comes to handling promises in TypeScript, I'm used to the then/catch style like this: .findById(id) .then((result: something | undefined) => result ?? dosomething(result)) .catch((error: any) => console.log(error)) However, I have also ...

Exploring the Benefits of Utilizing the tslint.json Configuration File in an Angular 6 Project

https://i.stack.imgur.com/j5TCX.png Can you explain the importance of having two tslint.json files, one inside the src folder and one inside the project folder? What sets them apart from each other? ...

Tips for utilizing generated *.d.ts files

I have been utilizing a Visual Studio 2017 extension called TypeScript Definition Generator to automatically create TypeScript interfaces for my MVC-ViewModels. Despite trying various similar tools, they all seem to result in the same output (*.cs.d.ts-Fil ...

DotLottie file loading issues

While using dotlottie/react-player, webpack 4, and react 16, I encountered module parse failed errors during compilation. "@dotlottie/react-player": "^1.6.5" "webpack": "^4.44.2", "react": "16.14.0&qu ...

The program encountered an error with code TS2339, indicating that the property "name" cannot be found on the type "never"

app.component.html I'm attempting to display the response data from my Firebase project using *ngFor. <div class="row"> <div class="col-md-3"> <h4 class="text-warning">All Employee Da ...

Determine the difference between dates using Angular 2's array filtering function

Here's a way to get the current time in seconds: let currentTimeInSeconds = new Date().getTime() / 1000; I have an array containing objects with an expirationDate property that returns expiration time in seconds. I can find the bills that have expir ...

Is there a way to programmatically add a timestamp to a form in Angular6?

Is there a way to automatically populate new forms with the current datetime value? this.editForm.patchValue({ id: chatRoom.id, creationDate: chatRoom.creationDate != null ? chatRoom.creationDate.format(DATE_TIME_FORMAT) : null, roo ...

What is the process for inheriting in JavaScript while also defining new prototype members as a singular object?

I find this code repetitive because it repeatedly uses Child.prototype: function Parent(a) { this.a = a; } function Child(a, b) { Parent.call(this, a); this.b = b; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = ...

Creating a custom type declaration for .lottie files in Next.js

https://i.sstatic.net/go6pV.png I've successfully integrated the module with no "can't find module" errors, and my code is functioning correctly. However, the main problem lies in the type declarations error, which prevents my code from recogni ...

Having difficulties generating ngc and tsc AOT ES5 compatible code

I've explored various options before seeking help here. I have an angular2 library that has been AOT compiled using ngc. Currently, I am not using webpack and solely relying on plain npm scripts. Below is the tsconfig file being utilized: { "comp ...

Set up a SQS queue to receive notifications from an SNS topic located in another AWS account by using AWS CDK in TypeScript

Looking to establish a connection between an SQS queue and an SNS topic located in a different account using CDK (TypeScript). Presented below is the code snippet (contained within a stack) that I believe should facilitate this integration. However, I have ...

Error: Module '...' or its type declarations could not be located

Recently, I attempted to deploy my next.js app on Vercel, only to encounter an error that read: "Type error: cannot find module '...' or its corresponding type declarations." After some investigation, I suspect this error is related to local modu ...

Is it possible for prettier to substitute var with let?

One of the tools I utilize to automatically format my Typescript code is prettier. My goal is to find out if there is a way to have prettier replace all instances of 'var' with 'let' during the formatting process. Below is the script I ...

Serialization of AspNetCore EntityModel to Json is not possible

I am currently tackling a project in AspNetCore involving EntityFrameworkCore and I am looking to utilize Ajax to retrieve an object. However, my controller is encountering issues when trying to serialize this object into Json format, causing my Ajax call ...