Is it possible to dynamically name keys in objects using template literals in Typescript?

Can the scenario below be achieved?

type test = <T extends string>(key: T, object: { [`${T}`]: number }) => void
                                                 ^^^^^^^^

I am aware that we can assign type literal values using that syntax, but after some experimentation, it seems that setting keys in the same way is not possible.

Nevertheless, theoretically, I believe it should be achievable given that mapped keys using as are feasible...

Does anyone have any insights into this?

Answer №1

If you want to utilize Record<T, number> (highly recommended) or stick with traditional method:

type example = <T extends string>(key: T, object: { [K in T]: number }) => void

Note that type objects behave differently than JS objects.

UPDATE

For additional fields, incorporate the & (merge) operator:

type example = <T extends string>(key: T, object: { [K in T]: number } & {foo: "bar"}) => void

Alternatively,

type example = <T extends string>(key: T, object: Record<T, number> & {foo: "bar"}) => 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

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

Poorly packaged library - Custom Angular library - Node Package Manager

Recently, I've been delving into the process of publishing a simple Angular library on NPM. Despite following various tutorials (like those found here, here, and here), I faced difficulties when attempting to use it in a test project. MY JOURNEY In s ...

In React TypeScript, the property types of 'type' are not compatible with each other

I have a unique custom button code block here: export enum ButtonTypes { 'button', 'submit', 'reset', undefined, } type CustomButtonProps = { type: ButtonTypes; }; const CustomButton: React.FC<CustomButtonProp ...

Enable Ace Editor's read-only mode

I'm having some difficulty getting my ace-editor to work in read-only mode. I'm working with Angular 9 and I've attempted the following approach: In my HTML file, I have the following code: <ace-editor mode="java" theme="m ...

Optional parameters in typed languages can either have zero or all parameters provided

I am delving into the world of typed functional programming and have embarked on implementing partial application with a focus on type safety. Issue at hand: I'm aiming to create a function that can take a function along with zero or all of its param ...

Tips for handling promises in a class getter method in TypeScript

In two of my classes, I use async/await functions to retrieve products from the product class. export default class Products { async getProducts() : Promise<[]> { return await import('../data/products.json'); } } export defa ...

Adding a new value to a string variable using TypeScript

Just starting out with Angular and I'm looking to capture user input from a text box with each keystroke and add it to a string variable like in Java. In my text box, I have the following setup for capturing key events: <input type="text" ...

Overriding a generic property in Typescript allows for a more

I'm troubleshooting an issue with my code: class Base<T> {} class Test { prop: Base<any>; createProp<T>() { this.prop = new Base<T>(); } } const test = new Test(); test.createProp<{ a: number }>(); test.pr ...

Modify information in formArray

Let's take a look at this setup I have: Model: export class MapDetailModel{ id: number; lat: number; lon: number; alt: number; long: number; angle: number; distance?: number; pendenza?: number; } Html: <div clas ...

The parameter type 'void' cannot be assigned to the parameter type 'SetStateAction<{}>'

Currently, I am in the process of developing an application utilizing TMDB with NextJS and Typescript. Within my movies.ts file, I have implemented the following code: export async function getTrendMovies() { const url = 'https://api.themoviedb.o ...

Leverage the power of TypeScript by enabling the noImplicitAny flag when working

Currently, I am looking to activate the noImplicitAny flag in my compiler. My main issue lies with utilizing lodash/fp as there are no typings available at this moment. Due to this, the compiler is generating errors due to the absence of a definition file ...

Issue with Angular and rxjs: Subscription provider not found

Trying to establish communication between a service and component in Angular, where the service holds a value and the component subscribes to its changes. Currently utilizing rxjs Subscription, but encountering an issue: Uncaught (in promise): Error: No p ...

Encountered an error while trying to access a property that is undefined - attempting to call

In my TypeScript class, I have a method that retrieves a list of organizations and their roles. The method looks like this: getOrgList(oo: fhir.Organization) { var olist: orgRoles[] = []; var filtered = oo.extension.filter(this.getRoleExt); f ...

Understanding the concept of a "class variable" in Typescript when referring to a variable that belongs to another class

When we declare a variable at the class level and assign it the type of another class, such as in the following code: let greeter: Greeter; //line 1 greeter = new Greeter("world"); What is contained within 'greeter' on line 1? ...

Leverage TypeScript with AngularJS to validate interpolation and binding within HTML documents

While TypeScript can detect compile errors for *.ts files, the question arises if these benefits can be extended to AngularJS views/templates. Consider a scenario where the code snippet below is present: <div ng-controller="HomeController as home"> ...

Typescript: Deciphering how to interpret a string with a mix of characters and numbers

Is there a way in TypeScript to add 40 to a variable of type string | number, and return a result as a string | number? My initial approach was to parse the variable to a number, then perform the addition, but how can I ensure that the variable is proper ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Modify the color of the matSnackbar

I'm having trouble changing the snackbar color in Angular using Angular Material. I tried using panelClass in the ts file and adding it to the global css, but the color remains unchanged. Any suggestions on how to resolve this? I am still new to this ...

Mapping through multiple items in a loop using Javascript

Typescript also functions Consider an array structured like this const elementList = ['one', 'two', 'three', 'four', 'five'] Now, suppose I want to generate components that appear as follows <div&g ...