Implement method functionality within TypeScript interfaces

I've encountered a scenario where I have an interface that will be utilized by multiple classes:

interface I {
  readonly id: string;
  process(): void;
}

My objective is to pass the id through a constructor like so:

class A implements I {...}
let a: A = {id: "my_id"} // or new A("my_id");

I'm looking for a way to avoid repeating the default constructor implementation in each class that implements the interface, for example:

class A implements I {
  constructor(id: string){ this.id = id }
}

Although I attempted to include the constructor implementation in the interface itself, I encountered a "cannot find id" error.

Is there a solution for this in TypeScript?

Answer №1

It is actually not possible, but you can find more information here.

One way to achieve similar results is by implementing the following code:

interface IMyInterface {
    readonly id: string;
    process(): void;
}

class ParentClass {
    id: string;
    constructor(id: string) {
        this.id = id;
    }
}

class SubClassOne extends ParentClass implements IMyInterface {
    process(): void {
        throw new Error('Method not implemented.');
    }
}
class SubClassTwo extends ParentClass implements IMyInterface {
    process(): void {
        throw new Error('Method not implemented.');
    }
}

const myclassOne = new SubClassOne('123');
const myclassTwo = new SubClassTwo('123');

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

When comparing TypeScript class functions with regular functions and variables, which one yields better performance?

When it comes to defining functions, is it better to use variables or functions directly? Also, how does this affect tree-shaking? I am dealing with a lot of calculation-intensive helper classes and I am unsure about the optimal approach in terms of memor ...

Arrange the items that are missing from Array B to be located at the bottom of Array A, organized in a file tree structure

I have two arrays containing different types of objects. Each object in the arrays has a title assigned to it. My goal is to compare these two arrays based on their titles and move any files that are not included in the bottom part of the fileStructure arr ...

Tips for utilizing the latest hook feature in Typegoose

After adding a pre hook on updateOne events, I noticed it functions differently compared to save events... I believe this discrepancy is due to the fact that the update command typically includes a matcher as its first argument. I attempted to capture the ...

Models in Typescript that are interrelated with Loopback

I'm currently working on defining connected models including the HasMany relationship in the context of @types/loopback definitions My approach involves creating an interface for HasMany and its implementation: interface IHasMany { /** ...

Managing a click event with an element in React using TypeScript

Hey there, I'm pretty new to TypeScript and React. I have this event where I need to identify the element that triggered it so I can move another element close to it on the page. However, I'm facing some challenges trying to make it work in React ...

Typescript types can inadvertently include unnecessary properties

It seems that when a class is used as a type, only keys of that class should be allowed. However, assigning [Symbol()], [String()], or [Number()] as property keys does not result in an error, allowing incorrect properties to be assigned. An even more curio ...

How can I identify and remove duplicate elements from an array of objects?

elements= [ { "id": 0, "name": "name1", "age": 12, "city": "cityA" }, { "id": 1, "name": "name2", "age": 7, "city": "cityC" }, { &qu ...

WebStorm displays all imported items as unused in a TypeScript backend project

https://i.stack.imgur.com/J0yZw.png It appears that the image does not display correctly for files with a .ts extension. Additionally, in .tsx files, it still does not work. In other projects using WebStorm, everything works fine, but those projects are o ...

Maintain the spacing of an element when utilizing *ngFor

Using Angular.js and *ngFor to loop over an array and display the values. The goal is to preserve the spaces of elements in the array: string arr1 = [" Welcome Angular ", "Line1", "Line2", " Done "] The ...

Tips for implementing a generic constant value in a TypeScript function

Is it permissible in TypeScript to have the following code snippet? function getFoo<P = "a"|"b">():string { // P represents a type, not an actual value! return "foo"; } getFoo<"a>">(); // no ...

Calling a typed function with conditional types in Typescript from within another function

In my attempt to create a conditional-type function, I stumbled upon this question on Stack Overflow. Unfortunately, it seems that the approach doesn't work well with default values (regardless of where the default value is placed). Following the advi ...

Having trouble with data types error in TypeScript while using Next.js?

I am encountering an issue with identifying the data type of the URL that I will be fetching from a REST API. To address this, I have developed a custom hook for usability in my project where I am using Next.js along with TypeScript. Below is the code sni ...

Error: Attempting to access an undefined property ('call') on Next.js is causing a TypeError

Exploring the realms of Next.js and Typescript for a new project! My goal is to utilize next.js with typescript and tailwind CSS by simply entering this command: npx create-next-app -e with-tailwindcss my-project Smooth sailing until I hit a snag trying t ...

Is there a way to apply a consistent style to all the fields of an object at once?

I have a formatting object named typography that includes various styles. One common issue I've encountered is that the line-height property is consistently set to 135%. Anticipating that this might change in the future, I am looking for a way to cent ...

Using a generic name as a JSON key in a TypeScript file

I received data from an API call const tradingApiResponse = { Timestamp: "2024-01-15T12:00:00", Ack: "Success", Version: 1, Build: "1.0.0", UserDeliveryPreferenceArray: { NotificationEnable: [ { EventType: ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

Exploring the differences between initializing class members and using setters and getters in Typescript

Here is the code snippet that I am working with: export class Myclass { private _someVal = 2; public get someVal() { return this._someVal; } public set someVal(val) { this._someVal = val; } } In my template, I have <span&g ...

Unable to save a dynamic FormArray within a FormGroup

My FormGroup consists of three FormControl fields and one FormArray field, as shown in the figure below. I need to collect the manager's name from the user. When the add button is clicked, the manager details should be displayed in a table. In the tab ...

Typescript custom react hook - toggling with useToggle

I developed a custom hook to toggle boolean values: import { useState } from 'react'; export function useToggle(initialValue: boolean) { const [value, setValue] = useState<boolean>(initialValue); const toggleValue = () => setValue ...

Is there a way to utilize multiple HTML templates with the same TypeScript file?

Is it possible to use different HTML templates for the same TypeScript file, based on an expression in the constructor? I am looking for something like this: <div class="container-fluid"> <app-teste1 *ngIf="teste == '1'> & ...