Generate an object in Typescript that includes a dynamic property calculated from an input parameter

Is there a way to achieve the following function in TypeScript?

function f<T extends 'a' | 'b'>(t : T): {[t]: ...} {
  return {[t]: ...}
}

This code is intended to make f('a') have type {'a': ...} and similarly for 'b'. However, TypeScript throws errors when trying to implement this. I've searched through resources like Stack Overflow, Stack Overflow post on object interfaces with variable keys, and the official documentation on mapped types, but haven't found a clear solution.

Can someone provide insights on how to make this work in TypeScript?

Answer №1

Are your requirements met with this solution?

type FReturnType<T extends string>={
  [property in T]: string;
};

function generateReturnType<T extends 'a' | 'b'>(input : T): FReturnType<T> {
  return {
    [input]: ''
  } as FReturnType<T>
}

let resultA = generateReturnType('a')

resultA.a // string
resultA.b //error


let resultB = generateReturnType('b')

resultB.b //string
resultB.a //error

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

Typescript encountering difficulty in accessing an array saved in sessionStorage

Imagine you have an array stored as a string in session storage, and you need to retrieve it, add an element, and then save it back. trackNavHistory = (path: String) => { let historyArr : Array<String> = sessionStorage.getItem("navHistory ...

Tips on customizing the Nuxt Route Middleware using Typescript

I am working on creating a route middleware in TypeScript that will validate the request.meta.auth field from the request object. I want to ensure this field has autocomplete options of 'user' and 'guest': export default defineNuxtRoute ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

Exploring the functionality of surveyjs in conjunction with react and typescript

Does anyone have any code samples showcasing how to integrate Surveyjs with React and TypeScript? I attempted to import it into my project and utilized the code provided in this resource. https://stackblitz.com/edit/surveyjs-react-stackoverflow45544026 H ...

Change to a dark theme using React hooks in typescript

Hello, I am new to React and English is not my first language, so please excuse any mistakes. I have been trying to enable a dark mode feature on my website. Most examples I have found involve toggling between dark and light modes where you need to specify ...

Struggle to deduce the generic parameter of a superior interface in Typescript

Struggling with the lack of proper type inference, are there any solutions to address this issue? interface I<T> {}; class C implements I<string> {}; function test<T, B extends I<T>>(b: B): T { return null as any; // simply for ...

Is it considered best practice to include try/catch blocks within the subscribe function in RxJs?

Imagine we have an Angular 2 application. There is a service method that returns data using post(), with a catch() statement to handle any errors. In the component, we are subscribing to the Observable's data: .subscribe( ()=> { ...

Verifying input for Numeric TextField

The text field being used is: <TextField variant="outlined" margin="normal" id="freeSeats" name="freeSeats" helperText={touched.freeSeats ? errors.freeSeats : ''} error={touched.freeSeats && Boolean(errors.fre ...

Is it possible to confirm that a value is a valid key without prior knowledge of the object's keys during compile-time?

Is there a way in TypeScript to declare that a variable is a keyof some Record without prior knowledge of the keys? For instance, consider an API response returning JSON data. Is it possible to define a type for the keys of this payload to ensure that whe ...

I am encountering a TypeScript error with URLSearchParams. The object cannot be successfully converted to a string using the toString() method

During the development of my react app with postgres, express, node, and typescript, I ran into an issue while working on the backend code. The problem arises when trying to utilize URLSearchParams. index.js import express from 'express'; import ...

What is the reason behind TypeScript not stating "When comparing a string to a null value, the condition will always return 'false'?"

When comparing a string to a number, an error and warning are generated. But why is there no warning when comparing a string to null/undefined? In this case, the type 'smth' is still narrowed to never without any warning displayed. The strictNul ...

How can I change a ReactNode into a text format?

I am looking for a way to convert the following code snippet into a string while preserving Tailwind CSS and other elements. My project uses Next.js with TypeScript and Tailwind CSS. Input : export default function Header_1() { return ( <div clas ...

Navigating the use of property annotations in Mapped Types with remapped keys

After exploring the concept of Key Remapping in TypeScript, as shown in this guide, I am wondering if there is a way to automatically inherit property annotations from the original Type? type Prefix<Type, str extends string> = { [Property in keyo ...

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 ...

Struggling with hashtags and ampersands in Angular when making an HTTP request

Dealing with Special Characters # and & in Angular's http.get() Request URL Take a look at my code first. Angular Service let versionsearch = "&"; let strweeksearch = "%23"; this.http.get(this.apiUrl + 'GetVersionInfo?vehicleVersion=' + v ...

Dealing with null-safe operators issues has been a challenge for me, especially while working on my Mac using

Hey everyone! I'm encountering errors when using null sage operators in TypeScript. Can someone help me figure out how to solve this issue? By the way, I'm working on Visual Studio Code for Mac. https://i.stack.imgur.com/huCns.png ...

Revise Swagger UI within toggle button switch

My project aims to showcase three distinct OpenApi definitions within a web application, enabling users to explore different API documentation. The concept involves implementing a toggle button group with three buttons at the top and the Swagger UI display ...

Searching for a specific document using AngularFirestore - what's the best method?

Is it possible to create an Observable that is limited to a single document? While the code provided creates an Observable for querying multiple documents: foo.component.ts import { AngularFirestore } from '@angular/fire/firestore'; import { O ...

Tips on personalizing the FirebaseUI- Web theme

Can someone help me find a way to customize the logo and colors in this code snippet? I've only come across solutions for Android so far. if (process.browser) { const firebaseui = require('firebaseui') console.log(firebaseui) ...

There was an error in calling `prisma.user.findUnique()`:

Here is my code snippet for the API route: export const POST = async (req: NextRequest) => { ... try { const { email, name, password } = await req.json(); console.info(email, name, password); const existingUser = await prismadb.user.findUn ...