Is it possible for me to create an interface that is derived from a specific type?

Is there a way to define an interface in TypeScript where the keys are based on a specific type? For example:

type FruitTypes = "banana" | "apple" | "orange";

interface FruitInterface {
  [key: string]: any; // should use FruitTypes as keys instead of string
}

// Desired output:
const FruitsObject: FruitInterface = {
  banana: "Banana",
  apple: "Apple",
  orange: "Orange",
  mango: "Mango" // This should cause an error
};

I attempted this approach:

interface FruitInterface {
  [key: keyof FruitTypes]: any;
}

Is there another method to achieve this?

Thank you in advance.

Answer №1

This operates in accordance with your requirements:

const FruitList: Record<FruitTypes, any>

Do you have a particular rationale for requiring an interface? An alternative approach could be:

interface FruitsInterface extends Record<FruitTypes, any> {}
const FruitList: FruitsInterface

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

Having trouble implementing object type switching in Typescript

While in the process of developing an angular application, I stumbled upon a peculiar issue. Some time ago, I crafted this piece of code which performed flawlessly: selectedGeoArea: any receiveStoreEvent(event) { switch (event.constructor) { ca ...

Modeling a potentially empty array in Typescript can be achieved by implementing specific interface definitions

Here is the current situation: type A = { b: string, c: number } I have an object that I will receive from an API, which could be either A[] or [] As of now, when I attempt to use it, const apiData: A[] || [] const b = apiData[0].a // I expected this to ...

Sending an event from a child component to another using parent component in Angular

My form consists of two parts: a fixed part with the Save Button and a modular part on top without a submit button. I have my own save button for performing multiple tasks before submitting the form, including emitting an Event to inform another component ...

Displaying errors to the user using Angular's HttpClient in an Ionic application

I am currently working on a small project and struggling to grasp certain TypeScript concepts. Specifically, I am trying to pass data from a form to an object and then send it via an HTTP service to an endpoint. The response is displayed in the console, in ...

When you use array[index] in a Reduce function, the error message "Property 'value' is not defined in type 'A| B| C|D'" might be displayed

Recently, I delved deep into TypeScript and faced a challenge while utilizing Promise.allSettled. My objective is to concurrently fetch multiple weather data components (such as hourly forecast, daily forecast, air pollution, UV index, and current weather ...

Why is my custom 404 page failing to load after building my Next.js application?

I recently set up a custom 404 page for my Next.js app and wanted to test it locally before deploying to the server. To do this, I used the "serve" package to host the project on my local machine. However, when I tried navigating to a non-existent page, th ...

Adjust the selected value in real-time using TypeScript

Hey there, I've got a piece of code that needs some tweaking: <div> <div *ngIf="!showInfo"> <div> <br> <table style="border: 0px; display: table; margin-right: auto; margin-left: auto; width: 155%;"& ...

Unable to spy on the second and third call using Jest

I'm having trouble using spyOn on the second and third calls of a function in my jest test I attempted to follow the documentation with this approach: it("should succeed after retry on first attempt failure", async () => { jest.spyOn(n ...

Guide to correctly passing custom parameters along with the event object to an asynchronous form submission handler

Asking for guidance on defining and typing custom parameters alongside the native event object in an async onSubmitHandler for a form. The current implementation only receives the native event as a single parameter: const onSubmitHandler: FormEventHa ...

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

The page does not appear to be updating after the onClick event when using the useState hook

Having difficulty re-rendering the page after updating state using the useState hook. Although the state value changes, the page does not refresh. export function changeLanguage(props: Props) { const [languageChange, setLanguageChange] = React.useState( ...

Guide on navigating to a specific page with ngx-bootstrap pagination

Is there a way to navigate to a specific page using ngx-bootstrap pagination by entering the page number into an input field? Check out this code snippet: ***Template:*** <div class="row"> <div class="col-xs-12 col-12"> ...

The specified type '{ rippleColor: any; }' cannot be assigned to type 'ColorValue | null | undefined'

I've been diving into learning reactnative (expo) with typescript, but I've hit a roadblock. TypeScript keeps showing me the error message Type '{ rippleColor: any; }' is not assignable to type 'ColorValue | null | undefined' ...

Enhance the Component Props definition of TypeScript 2.5.2 by creating a separate definition file for it

I recently downloaded a NPM package known as react-bootstrap-table along with its type definitions. Here is the link to react-bootstrap-table on NPM And here is the link to the type definitions However, I encountered an issue where the types are outdate ...

Transforming a flat TypeScript array into a nested object structure

I'm working on implementing a user interface to offer a comprehensive overview of our LDAP branches. To achieve this, I plan to utilize Angular Materials Tree as it provides a smooth and intuitive browsing experience through all the branches (https:// ...

Issue in Ionic 2: typescript: The identifier 'EventStaffLogService' could not be located

I encountered an error after updating the app scripts. Although I've installed the latest version, I am not familiar with typescript. The code used to function properly before I executed the update. cli $ ionic serve Running 'serve:before' ...

Strategies for navigating dynamic references in Angular 2 components

I am working with elements inside an ngFor loop. Each element is given a reference like #f{{floor}}b. The variable floor is used for this reference. My goal is to pass these elements to a function. Here is the code snippet: <button #f{{floor}}b (click) ...

When the value of a react state is used as the true value in a ternary operator in Types

Attempting to implement sorting on a table is resulting in the following error: (property) direction?: "asc" | "desc" No overload matches this call. Overload 1 of 3, '(props: { href: string; } & { active?: boolean; direction? ...

What is the best method to condense an array or extract only the valid values?

Looking to find the total count of properties that are true from an array of objects? Here's an example: let data = [ { comment: true, attachment: true, actionPlan: true }, { whenValue: '', ...

Warning from Cytoscape.js: "The use of `label` for setting the width of a node is no longer supported. Please update your style settings for the node width." This message appears when attempting to create

I'm currently utilizing Cytoscape.js for rendering a dagre layout graph. When it comes to styling the node, I am using the property width: label in the code snippet below: const cy = cytoscape({ container: document.getElementById('cyGraph&apo ...