Provide a string argument when instantiating an abstract class

I am searching for a method to assign a name string within a class and utilize it in the abstract class at the constructor level, without the need for a function. Opening up the constructor is not an option due to using typedi.

You can access the playground link here.

Uncaught TypeError: this.name is not a function

abstract class Root {
    abstract name(): string
    notFoundError = new Error(`${this.name()} not found`)

}

class Use extends Root {
    name = () => 'User'
}

const x = new Use()
throw x.notFoundError

This approach is not what I'm seeking:

abstract class Root {
    abstract name: string
    notFoundError = () => new Error(`${this.name} not found`)

}

class Use extends Root {
    name = 'User'
}

const x = new Use()
throw x.notFoundError()

I am specifically interested in notFoundError not being treated as a function.

Answer №1

Here's a concept:

const Parent = (type: string) => { 
    abstract class Parent {
        type: string = type
        errorMessage = new Error(`${this.type} not found`)
    }
    return Parent
}

class Child extends Parent('Product') {

}

const y = new Child()
throw y.errorMessage

Answer №2

Instead of assigning the value 'User' to the variable name using name = 'User' or name = () => 'User', it is recommended to use name() { return 'User' }.

abstract class Root {
    abstract name(): string
    notFoundError = new Error(`${this.name()} not found`)

}

class Use extends Root {
    name() { return 'User' }
}

const x = new Use()
throw x.notFoundError

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

Leveraging an intersection type that encompasses a portion of the union

Question: I am currently facing an issue with my function prop that accepts a parameter of type TypeA | TypeB. The problem arises when I try to pass in a function that takes a parameter of type Type C & Type D, where the intersection should include al ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Ways to retrieve the key of an enum based on its value within Typescript

Here's an example of an enum: export enum Colors { RED = "RED COLOR", BLUE = "BLUE COLOR", GREEN = "GREEN COLOR" } Can you help me figure out how to retrieve the enum key based on a specific value? For instance, if I input "BLUE COLOR", ...

What is preventing the combination of brand enums in Typescript 3?

Utilizing brand enums for nominal typing in TypeScript 3 has been a challenge for me. The code snippet below demonstrates the issue: export enum WidgetIdBrand {} export type WidgetId = WidgetIdBrand & string; const id:WidgetId = '123' as Wi ...

Unlocking the Power of Data Passing Through Tabs

My Application Structure Client Module - Material Tab Tab 1 - Customer Table View Tab 2 - Edit Customer View <mat-tab-group> <mat-tab label="View"> <div> <app-customer-table></app-customer-table> & ...

Incorporating a Symbol into a Function

Reviewing the following code snippet: namespace Add { type AddType = { (x: number, y: number): number; }; const add: AddType = (x: number, y: number) => { return x + y; }; } Can a 'unique symbol' be added to the AddType lik ...

Creating a game of Black Jack using a prebuilt deck class

In our recent class assignment, we were tasked with implementing the ArrayBag class, which is widely available online. The next step is to utilize this class to create a Black Jack game. However, I am facing some challenges in figuring out how to proceed w ...

In React TS, the function Window.webkitRequestAnimationFrame is not supported

I'm facing an issue where React TS is throwing an error for window.webkitRequestAnimationFrame and window.mozRequestAnimationFrame, assuming that I meant 'requestAnimationFrame'. Any suggestions on what to replace it with? App.tsx import Re ...

Is it possible to swap out the Firestore module `doc` with the `document` module

I enjoy using the Firebase version 9 modules, however, I find that doc is not to my liking. It would be better if it were document, similar to how collection is not shortened to col. The following code does not function as expected: import { doc, collecti ...

Develop a query builder in TypeORM where the source table (FROM) is a join table

I am currently working on translating this SQL query into TypeORM using the QueryBuilder: SELECT user_places.user_id, place.mpath FROM public.user_root_places_place user_places INNER JOIN public.place place ON place.id = user_places.place_id The ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving thi ...

Using a class variable within a member function declaration in Python-3: A guide

I have a scenario where I've defined a class as follows: class foo: def __init__(self, a): self.a = a Now, I want to set the member variable object "a" as a default argument for a member function of this class. Here's what I tried: ...

Creating a type-safe dictionary for custom theme styles in Base Web

In my Next.js project, I decided to use the Base Web UI component framework. To customize the colors, I extended the Theme object following the guidelines provided at . Interestingly, the documentation refers to the theme type as ThemeT, but in practice, i ...

Tips for effectively managing loading and partial states during the execution of a GraphQL query with ApolloClient

I am currently developing a backend application that collects data from GraphQL endpoints using ApolloClient: const client = new ApolloClient({ uri: uri, link: new HttpLink({ uri: uri, fetch }), cache: new InMemoryCache({ addTypename: f ...

Experimenting with a file system library function using Jest and Typescript alongside a placeholder function

When attempting to test a library function that uses the fs module, I received assistance in this question on Stack Overflow. The feedback suggested avoiding mocks for better testing, an approach I agreed with @unional. I am now facing a similar challenge ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...

Encounter an error message "Expected 0 type arguments, but received 1.ts(2558)" while utilizing useContext within a TypeScript setting

Encountering the error mentioned in the title on useContext<IDBDatabaseContext> due to the code snippet below: interface IDBDatabaseContext { db: IDBDatabase | null } const DBcontext = createContext<IDBDatabaseContext>({db: null}) Despite s ...

TypeScript is throwing an error because a value has been declared but never actually used in the

private tree_widget: ITreeWidget; private $ghost: JQuery | null; private drag_element: DragElement | null; private previous_ghost: IDropHint | null; private open_folder_timer: number | null; constructor(tree_widget: ITreeWidget) { this.tree_widget = t ...

An issue arises in VueJS when employing brackets and the replace function in Typescript

My journey with the Typescript language has just begun, and I am excited to dive deeper into it. Currently, I am working on a SPA-Wordpress project as a hobby using Vite (VueJS). However, I am facing some challenges with the syntax when transitioning from ...

Ionic - Smooth horizontal tab scrolling for sorted categories

Currently, we are developing a web/mobile application that includes horizontal scroll tabs to represent Categories. While this feature works well on mobile devices, it requires additional functionality for web browsers. Specifically, we need to add two arr ...