Designing a TypeScript class that incorporates an interface

Struggling to grasp the correct syntax, I am looking to incorporate an interface into my project.

The desired interface for implementation is as follows:

interface Test {
  [name : string] : (source : string) => void;
}

My understanding is that this interface essentially consists of a object with strings as keys and functions as values.

Any guidance on this matter would be greatly appreciated.

Edit : Encountering multiple errors such as "incorrect implementation of interface", "index signature is missing", etc,

For a demonstration, refer to this playground example: Link

I did not write the implementation code for this interface, it comes from a preexisting sdk

Answer №1

To include the index signature in the class, follow this code snippet:

interface Example {
    [key: string]: (data: string) => void;

}

class ExampleClass implements Example {
    [key: string]: (data: string) => void; // Make sure to add this
    getFirstName(data: string) {
        console.log("example"); 
    }
}

Answer №2

It is not possible for a class to adhere to this particular interface.

This interface is more suitable for defining the structure of a "typed object."

You can define an object type with string keys and values that are functions taking a string argument and returning nothing.

For example:

let myObj: Test = {
    test: (source: string) => { console.log('function returning void'); }
};

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

Prevent updating components when modifying state variables

Introduction I've developed a React component that consists of two nested components. One is a chart (created with react-charts) and the other is a basic input field. Initially, I have set the input field to be hidden, but it becomes visible when the ...

Unlocking the ability to retrieve data generated by the context within getServerSideProps beyond its boundaries (for transitioning from Create React App to Next.js)

I am currently utilizing Create React App for my react application but I am in the process of migrating to Next.js. Accessing URL data such as host, protocol, and query parameters has posed a significant challenge. After some trial and error, I realized t ...

Can TypeScript be used to generate a union type that includes all the literal values from an input string array?

Is it feasible to create a function in TypeScript that takes an array of strings and returns a string union? Consider the following example function: function myfn(strs: string[]) { return strs[0]; } If I use this function like: myfn(['a', &a ...

Webpack may suggest, "An extra loader might be needed" within a React.js project

I recently created a React project with two separate workspaces, named 'webmail' and 'component'. In the 'component' workspace, I added a small tsx file that I wanted to utilize in the 'webmail' workspace. Below is t ...

Retrieving the value of an object using a key in TypeScript

Is there a way to create an object using keys from another object and determine the type based on a string? For example: const result = rebuild(query, { name: 'string' }); // query - { name: '123', dont_need: true } // result - { n ...

Ng2-NoUISlider displaying consistent range values

I'm facing an issue with implementing multiple sliders on a single page where each slider should have different range values. Here is a snippet of my HTML: <div *ngFor="let property of comepleteFilters"> <h5>{{property.pro ...

Troubleshooting Typescript Compilation Error in React - Cannot assign type 'Element' to type 'FunctionComponent<{}>'

The code snippet originally utilized - import { Create } from '@material-ui/icons'; <DroppableFolder count={draftsCount} sidebarOpen={open} folderId={FolderType.Drafts} Icon={Create} name="Dr ...

Angular 6: Issues with API Get Method not executing when an integer value is passed with an empty string

I'm experiencing an issue in my angular application when trying to call an API method from angular. The method requires two parameters - one integer value and one string value, which is optional. Below is the code snippet in Typescript: let id:numbe ...

Using useRef with Typescript/Formik - a practical guide

Encountering Typescript errors while passing a ref property into my custom FieldInput for Formik validation. Specifically, in the function: const handleSubmitForm = ( values: FormValues, helpers: FormikHelpers<FormValues>, ) => { ...

Add a feature to a functional component that is enclosed with React.forwardRef

Within my codebase, there exists a component that is wrapped with React.forwardRef and serves as a compound component. One challenge I encountered was how to preserve the functionality of Form.Item = FormItem; while still having the Form component fun ...

What is the best way to apply a CSS class to a ComponentRef that has been generated in Angular 5

I am attempting to dynamically add a CSS class to a component right after its creation by utilizing ViewContainerRef and ComponentFactoryResolver. My goal is to determine the class based on which other Components have already been added to myViewContainerR ...

Data from graphql is not being received in Next.js

I decided to replicate reddit using Next.js and incorporating stepzen for graphql integration. I have successfully directed it to a specific page based on the slug, but unfortunately, I am facing an issue with retrieving the post information. import { use ...

The type '{ domain: string; parent: string; }' cannot be assigned to type 'string'. Error code: ts(2322)

Hello there! I am new to TS, so thank you for taking the time to read this. The problematic line in my code is: <this.RenderPostLink domain={r.domain} parent={r.parent} /> where I encounter an error. RenderImages = (): React.ReactElement => ...

The source files are expected to be contained within the 'rootDir' directory, which is not located at 'c:/Users/hasit/Desktop/typescript/src'

Can someone assist me with separating the Src folder and public folder in my project? When I try to do it in the tsconfig.json file, I encounter this error: "'rootDir' is expected to contain all source files." I have followed instructions from a ...

Incorporating HTTP status codes into error handling

I have developed an API where I've organized the services separately from the controllers. In my service functions, I've included basic checks to trigger errors when certain conditions are met. Currently, my controller function just returns a 500 ...

Guide on converting a JSON object into a TypeScript Object

I'm currently having issues converting my JSON Object into a TypeScript class with matching attributes. Can someone help me identify what I'm doing wrong? Employee Class export class Employee{ firstname: string; lastname: string; bi ...

"Ionic Calendar 2 - The ultimate tool for organizing your

I am using a calendar in my Ionic app that retrieves events from a database through an API. var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://portalemme2.com.br/SaoJoseAPI/agenda', true); this.http.get('http://portalemme2.c ...

The attribute 'map' is not found on the data type 'Observable<[{}, {}]>'

Struggling to incorporate map, PublishReplay, and other rxjs functions into Angular6, I keep encountering a compilation error stating "Property 'map' does not exist on type 'Observable<[{}, {}]>'" every time. The same issue arises ...

Experience the dynamic live preview feature of Sanity integrated with NextJS 13

I am facing an issue with checking if preview mode is activated on my website. While following a YouTube tutorial, I realized that the instructions may be outdated with the latest NextJS update. This was the code snippet I was originally working with to ...

The issue in Angular2 viewmodel where the boolean value fails to update the *ngIf template

I'm seeking assistance with an unusual issue in my Angular2 and Typescript application. Within my template, I have the following HTML utilizing ngIf: <div *ngIf="loading" class="row"> <div class="small-3 small-centered columns" > ...