[Simple TypeScript]: Assign the parameter value as the key of the object returned by the function

How do I modify the key of a function returned object to match its parameter's value?

Here is my current code:

const createCache = <A, T extends string>(name: T, base = {}) => {
  const cache = base;

  return {
    [name]: cache,
  } as {
    [key in keyof T]: typeof cache; // this didn't work
    // [key in typeof name]: typeof cache; // this didn't work
    // [key in keyof typeof name]: typeof cache; // this didn't work
    // [key: typeof name]: typeof cache; // this didn't work
  };
};

I am attempting to implement an autocomplete feature with the returned value matching the key:

createCache('root').root // okay
createCache('hello').hello // okay

makecache('error').notError // error!

I have successfully achieved this before, but I cannot recall how.

Answer №1

This method appears to work effectively:

const createStorage = <A, T extends string>(item: T, base = {}) => {
  const storage = base;

  return {
    [item]: storage,
  } as {
    [key in typeof item]: typeof storage
  };
};

createStorage('error').error // triggers an error message

Link

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

Create an array filled with multiple arrays containing objects

To achieve the desired array of array of objects structure, I need to populate the data like this: let dataObj = [ [ { content: "test1"}, { content: "test2"}, { content: "test3"} ], [ ...

How can I display an ngx spinner after a delay of 1 second?

I am uncertain about the answer I came across on this platform. intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { const time = 900; const spinnerLogic = () => { if (this.isRequestServed ...

What is the best way to organize my NPM package with separate directories for types and functions?

I am currently working on developing a custom NPM package that will serve as a repository for sharing types and functions across my project. Let's name this project wordle. Given the emphasis on types, it is worth noting that I am using TypeScript for ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...

Passing a custom data type from a parent component to a child component in React

I'm currently working on developing a unique abstract table component that utilizes the MatTable component. This abstract table will serve as a child element, and my goal is to pass a custom interface (which functions like a type) from the parent to t ...

How can I retrieve the `checked` state of an input in Vue 3 using Typescript?

In my current project, I am using the latest version of Vue (Vue 3) and TypeScript 4.4. I am facing an issue where I need to retrieve the value of a checkbox without resorting to (event.target as any).checked. Are there any alternative methods in Vue tha ...

Tips for securely encrypting passwords before adding them to a database:

While working with Nest.Js and TypeORM, I encountered an issue where I wanted to hash my password before saving it to the database. I initially attempted to use the @BeforeInsert() event decorator but ran into a roadblock. After some investigation, I disc ...

Struggling with setting up Angular Material and SCSS configuration in my application -

Hey there, I encountered an error or warning while trying to launch my angular app. Here's the issue: ERROR in ./src/styles/styles.scss (./node_modules/@angular-devkit/build- angular/src/angular-cli-files/plugins/raw-css- loader.js!./n ...

The object literal can only define properties that are already known, and 'data' is not found in the type 'PromiseLike<T>'

When making a request to a server with my method, the data returned can vary in shape based on the URL. Previously, I would cast the expected interface into the returned object like this: const data = Promise.resolve(makeSignedRequest(requestParamete ...

Is it feasible to alter the TypeScript interface for the default JavaScript object (JSON)?

When dealing with cyclic objects, JSON.stringify() can break (as mentioned in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value) An alternative solution suggested in the same article is to use 'cycle.js&apos ...

Encountering a duplication issue when redirecting components in Angular2/TypeScript using navigateByUrl

Seeking guidance on implementing the login function where the current component redirects to another one upon clicking the login button. Below are my .ts and .html files: login.component.ts login.component.html The issue arises when using npm start for ...

Encountering a Difficulty while attempting to Distinguish in Angular

I am currently working on a form where I need to dynamically add controls using reactiveForms. One specific task involves populating a dropdown menu. To achieve this, I am utilizing formArray as the fields are dynamic. Data: { "ruleName": "", "ruleD ...

The Ajax auto-complete text box feature in ASP.NET is not functioning properly when used within a master page

This code snippet functions properly on a standard asp.net page. However, when used with a master page, it encounters issues. The masterpage.master <asp:TextBox ID="TextBoxSearchCompany" class="form-control" placeholder="Search company..." runat="ser ...

I was able to use the formGroup without any issues before, but now I'm encountering an error

<div class="col-md-4"> <form [formGroup]="uploadForm" (ngSubmit)="onSubmit(uploadForm.organization)"> <fieldset class="form-group"> <label class="control-label" for="email"> <h6 class="text-s ...

Nestjs is throwing an UnhandledPromiseRejectionWarning due to a TypeError saying that the function this.flushLogs is not recognized

Looking to dive into the world of microservices using kafka and nestjs, but encountering an error message like the one below: [Nest] 61226 - 07/18/2021, 12:12:16 PM [NestFactory] Starting Nest application... [Nest] 61226 - 07/18/2021, 12:12:16 PM [ ...

In React Typescript, there is an issue with react-router v4 where the Route component does not pass its props to the specified component

Struggling with React Router v4 and history usage in Browserrouter. Whenever attempting to access this.props.history.push("/"), the error pops up: TS2339: Property 'history' does not exist on type 'Readonly<{ children?: ReactNode; }> ...

Route.get() is expecting a callback function, however it received an object of undefined instead

In my nodejs application using typescript, I am working on separating the routing by introducing interfaces and controllers to handle the logic. app.ts const countryRoutes = require('./routes/countryroute') app.use('/countries', count ...

Angular 4 HTTP Requests Failing to Retrieve JSON Data

I am currently working with the following method in my Typescript: allPowerPlants(onlyActive: boolean = false, page: number = 1): PowerPlant[] { const params: string = [ `onlyActive=${onlyActive}`, `page=${page}` ].join('&&apo ...

The refresh function in the table is not working as expected when implemented in a functional component. The table being used is Material

I am currently utilizing MaterialTable from https://material-table.com/#/docs/features/editable to manage data and perform CRUD operations within my application. I am seeking a way to automatically refresh the table data after any CRUD operation (add, upda ...

Can Next.js accommodate server-side redirection with internationalization?

I'm working on a small Next.js app that has pages accessible only to logged in users. To manage the authenticated routes, I created an HOC (withAuth) that handles redirection on the server side to prevent page flashing on the client side. Everything i ...