What is the method for obtaining a literal type through a function parameter to use as a computed property name?

Can you help me with this code snippet?

const fn = (name: string) => {
  return { [name]: "some txt" };
};

const res = fn("books"); // books or any other string

The type of res recognized by TS is:

const res: {
  [x: string]: string;
}

I want to specify that res should have a property called books

const res: {
  books: string;
}

I've tried different approaches but nothing seems to be working. Is it even possible to achieve this? Or is it a known limitation in TypeScript?

Answer №1

To solve this issue, you can create a generic function in the following way:

const generateValue = <T extends string>(property: T): { [key in T]: string } => {
  return { [property]: "some text" } as any;
};

const result = generateValue("items");

This workaround is necessary due to TypeScript's limitation on allowing such syntax. You can test it out yourself 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

Is it considered best practice to pass an argument that represents an injectable service?

Is it a good practice to pass an argument that is an injectable service to a function? Hello everyone, I have been doing some research but have not found a definitive answer to the question above yet. I am currently working with Angular and came across so ...

Mastering Angular Apollo Error Resolution Methods

Hey everyone, I'm facing a problem with apollo-angular and apollo-link-error that I just can't seem to figure out. I've experimented with different approaches but have had no luck catching errors on the client-side of my angular web app. Bel ...

Steps for importing a CommonJS module that exports as a callable into TypeScript

I am dealing with a project that has a mixture of JavaScript and TypeScript files. Within the project, there is a JS library that follows this structure: module.exports = () => { // logic dependent on environment variables // then... return { ...

An issue occurred while trying to use a function that has a return type of NextPage

After successfully implementing the code below: const HomePage: NextPage = () => ( <div> <div>HomePage</div> </div> ); I wanted to adhere to Airbnb's style guide, which required using a named function. This led me t ...

What is the method for adding local images to FormData in Expo version 48 and above?

When working with Expo v47 and its corresponding React Native and TypeScript versions, FormData.append had the following typing: FormData.append(name: string, value: any): void An example of appending images using this code could be: const image = { uri ...

Update the nest-cli.json configuration to ensure that non-TypeScript files are included in the dist directory

I've been searching for a solution for hours now: I'm developing an email service using nestJS and nest mailer. Everything was working fine until I tried to include a template in my emails. These templates are hbs files located in src/mail/templ ...

Set the class function to be uninitialized

I'm a little unsure of my TypeScript knowledge. I have a class MyClass with a member variable that is a function, but I don't know what this function will be at compile time. I want to allow external code to set this function dynamically during r ...

The type 'Navigator' does not have the property 'userAgentData' in its definition

Since I'm looking to minimize the information provided by navigator.userAgent, I decided to migrate to User-Agent Client Hints. However, I've encountered an error while attempting to do so: https://i.stack.imgur.com/lgIl7.png Could someone plea ...

Nested self-referencing in Typescript involves a structure where

Please note that the code below has been simplified to highlight a specific issue. The explanation before the code may be lengthy, but it is necessary for clarity. Imagine I have a Foo class that represents a complex object. interface Config { bars:{ ...

Getting around using Material-UI Icons

Is it possible to utilize a Material-UI Icon for navigation using React Router Dom? I attempted the following approach without success: <NavigateBeforeIcon path="/vehicles"></NavigateBeforeIcon> With buttons, I am able to use component={Link ...

Utilizing node-canvas to import a .ttf file into TypeScript for registering a custom font

I am trying to incorporate locally stored fonts (in ttf format) into a canvas that is generated using node-canvas. To achieve this, I have created a typings file and included it in my tsconfig: fonts.d.ts declare module '*.ttf'; The fonts hav ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

Attempting to incorporate an npm package (specifically Howler) into an Angular 2 application

I'm facing an issue with importing Howler into my Angular 2 app as it doesn't have a typings file. Despite my efforts in searching for a solution, I haven't been able to find anything helpful. Can someone guide me on how to import "howler" i ...

What is the correct way to initialize and assign an observable in Angular using AngularFire2?

Currently utilizing Angular 6 along with Rxjs 6. A certain piece of code continuously throws undefined at the ListFormsComponent, until it finally displays the data once the Observable is assigned by calling the getForms() method. The execution of getForm ...

Utilize Page.evaluate() to send multiple arguments

I am facing an issue with the Playwright-TS code below. I need to pass the email id dynamically to the tester method and have it inside page.evaluate, but using email:emailId in the code throws an undefined error. apiData = { name: faker.name.firstNa ...

Why is it not possible to declare an interface or type within a TypeScript class?

I am struggling to define interface | type within a TypeScript class. Here is the code snippet: class MyClass { interface IClass { name: string, id: string } } However, I keep encountering this error: Unexpected token. A constructo ...

Issue with Socket.io: Data not received by the last user who connected

I have developed a Node.js and Express application with real-time drawing functionality on canvas using socket.io version 1.7.2. Users are divided into separate socket rooms to enable multiple teams to draw independently. However, there is an issue where t ...

The upcoming construction of 'pages/404' page will not permit the use of getInitialProps or getServerSideProps, however, these methods are not already implemented in my code

Despite my efforts to search for a solution, I have not found anyone facing the same issue as me. When I execute next build, an error occurs stating that I cannot use getInitalProps/getServerSideProps, even though these methods are not used in my 404.tsx f ...

Issue with IntelliJ: TypeScript Reference Paths Are Not Relative

I am currently using IntelliJ as my IDE, but I am facing an issue with configuring gulp-typescript to compile my typescript code. The problem arises from the fact that IntelliJ does not treat my reference paths relatively, instead it references them from m ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...