Ways to expand interface using an anonymous class

Let's say we have an anonymous class:

const AnonymousClass = class {}
let a: typeof AnonymousClass;

Is it possible to extend an interface from it? The compiler throws an error with this code:

interface I extends typeof AnonymousClass {

}

Here is the link to the playground for testing: https://www.typescriptlang.org/play/#src=const%20AnonymousClass%20%3D%20class%20%7B%7D%0D%0A%0D%0Alet%20a%3A%20typeof%20AnonymousClass%3B%0D%0A%0D%0Ainterface%20I%20extends%20typeof%20AnonymousClass%20%7B%0D%0A%0D%0A%7D

Answer №1

In the context of using an extends or implements clause, you cannot directly employ an expression. However, a workaround is to create a type alias and utilize that instead. Interestingly, you can even assign the same name as the anonymous class (const) since they reside in separate spaces (value space vs type space).

const AnonymousClass = class {
    static staticField = 0;
    instanceField = 0;
}

let a: typeof AnonymousClass;
type AnonymousClass = typeof AnonymousClass
interface I extends AnonymousClass {

}
let foo: I;
foo.instanceField // invalid
foo.staticField // valid

The above code snippet extends the static interface of the class. If your intention is to extend the instance interface instead, you can achieve this by using an additional InstanceType conditional type:

const AnonymousClass = class {
    static staticField = 0;
    instanceField = 0;
}

let a: typeof AnonymousClass;
type AnonymousClass = InstanceType<typeof AnonymousClass>
interface I extends AnonymousClass {

}

let foo: I;
foo.instanceField // valid
foo.staticField // invalid

Access Playground link here

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

Extracting live TV channels from an m3u file by differentiating them from VOD content

Currently, I am developing an IPTV player app and have successfully parsed the m3u file. My current challenge is separating live TV channels from Video on Demand (VOD). I am unsure of where exactly the transition happens in the playlists. Below are the ke ...

Is it necessary for 'ts-loader' to have 'typescript' installed in order to function properly? I personally did not encounter any issues with this

The npm documentation for using ts-loader suggests installing typescript. The official Typescript guide in webpack documentation also recommends the same, but without providing a clear explanation. However, I have successfully built everything without havi ...

Automatically divide the interface into essential components and additional features

Consider the following interfaces: interface ButtonProps { text: string; } interface DescriptiveButtonProps extends ButtonProps { visible: boolean, description: string; } Now, let's say we want to render a DescriptiveButton that utilize ...

Heroku: Unable to retrieve resource - server returned a 404 (Not Found) status code

I successfully developed my Angular 6 app on my local machine with everything working perfectly. However, after deploying the project to Heroku and running my app here Testing App, I encountered an error in the console browser. Failed to load resource: ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

The TSOA Express application is experiencing difficulties in retrieving endpoints

Currently, I am working on developing a REST API using node.js and Typescript. To aid in the documentation process, I am utilizing tsoa and swagger. The build process is successful, and the swagger.json file is generated without any issues. However, when a ...

Typescript: Why Lines Are Not Rendering on Canvas When Using a For-Loop

What started out as a fun project to create a graphing utility quickly turned into a serious endeavor... My goal was simple - to create a line graph. Despite my efforts, attempting to use a for-loop in my TypeScript project resulted in no output. In the ...

Why do I always seem to encounter issues when I start up the server?

An issue with Syntax Error has occurred: Failed to load plugin '@typescript-eslint' as declared in 'package.json » @vue/eslint-config-typescript/recommended » ./index.js'. The module '@typescript-eslint/eslint-plugin' could ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Tips for calculating the total of keyup elements in an Angular application

There are "N" inputs in a formgroup that need to be summed: <input (keyup)="sum($event)" type="text" name="estoque_variacao{{i}}" class="form-control" id="estoque_variacao{{i}}" formControlName="estoque_variacao"> This is the Typescript code: sum( ...

Issue with "Encountered error while attempting to differentiate..."

Utilizing Angular4 along with PrimeNG has been my choice for development. To prevent template repetition in my HTML file, I opted to use the ng-container. However, upon implementing the ng-container, an error surfaced: Error: Error trying to diff ' ...

What is the best way to incorporate a WYSIWYG Text Area into a TypeScript/Angular2/Bootstrap project?

Does anyone know of a WYSIWYG text editor for TypeScript that is free to use? I've been looking tirelessly but haven't found one that meets my needs. Any recommendations or links would be greatly appreciated. Thank you in advance! ...

In order to emphasize the chosen list item following a component refresh

SCENARIO: Let's consider a scenario where I have a component named list, responsible for displaying a list of all customers. Within this list, certain conditions are set up as follows: 1) Initially, the 1st list-item (e.g. Customer 1) is selected by ...

What is the best way to transfer the useState set state function to a child component in TypeScript?

Since delving into typescript, I've encountered an issue with passing a useState setter function. My parent component looks like this: const [word, setword] = useState('run') When passing props to the child component, it's done as fol ...

Retrieve the component's name using ReactElement.type.name

In my current project, I am working with React and Typescript. I need to retrieve the name of a functional component, which I have discovered can be accessed through the 'type' property of the component like this: component.type.name. Initially, ...

The placement of the FirebaseAuth.onAuthStateChanged call in an Angular application is a common concern for developers

Where is the best place to add a global listener initialization call in an Angular app? Take a look at this code snippet: export class AuthService { constructor( private store: Store<fromAuth.State>, private afAuth: AngularFireAuth ) { ...

Configuring Monaco Editor in React to be in readonly mode

Here is a code snippet to consider: import React from "react"; import Editor from "@monaco-editor/react"; function App() { return ( <Editor height="90vh" defaultLanguage="javascript" defa ...

Unable to find the relative path for the proto file: src/app/protos/greet.proto does not exist in the directory

https://i.sstatic.net/lxvWN.png I recently attempted to create a gRPC Angular client by following the steps outlined in this article: here During the process, I encountered an issue while running the command: protoc --plugin=protoc-gen-ts="{ABSOLUTE ...

Changes made to the source files in Webpack dev server combined with React and Typescript are not being successfully

I'm embarking on a new project to develop a small app using React, TypeScript, and Webpack for building. I found this helpful article to guide me through the process: https://www.typescriptlang.org/docs/handbook/react-&-webpack.html All the proje ...

Angular: controller's property has not been initialized

My small controller is responsible for binding a model to a UI and managing the UI popup using semantic principles (instructs semantic on when to display/hide the popup). export class MyController implements IController { popup: any | undefined onShow(con ...