Is there a method for creating TypeScript definitions that generates members dynamically?

While I'm not completely satisfied with the title of this question, I struggled to come up with something better at the moment.

I have a feeling that what I am looking for may not be supported, but I am willing to be proven wrong!

Currently, I am working with an API where the member names in the object returned can vary based on the query.

For example:

GetInfo(languages?:string[]);
GetInfo() => { name: "Cologne" };
GetInfo(["en", "de"]) => { name: "Cologne", name_en: "Cologne", name_de: "Köln" };

My question is, is there a method to create a definition that will automatically generate the name_{language} members?

Answer №1

Manipulating property names by concatenating strings to create type-checked properties is not supported in this way.

The workaround is to return an object with properties that have the same names as the language names:

function GetInfo<T extends string>(langs: T[]): Record<T | 'default', string>{
  return null as any;
}
let values = GetInfo(["en", "de"]) // values is  { en: string; de: string; default: string  }
values.default
values.de
values.en

A GitHub issue suggests adding support for string literal manipulations, but it's currently not on the roadmap.

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

Parent Class implementation for dynamic loading of components

I have been working on creating a new code for dynamic component loading using a parent-child relationship. The child component is set to override the parent and will be used for dynamically loading components. I found this useful link that guided me throu ...

Creation of source map for Ionic 2 TypeScript not successful

Struggling with debugging my Ionic 2 application and in need of guidance on how to include souceMap for each typescript file that corresponds to the javascript files. Despite enabling "sourceMap":true in my tsconfig.json file, the dev tools in Chrome do n ...

What is the purpose of adding "/dist" to the library import statement?

Currently, I am in the process of developing a react component library using vite as my primary build tool. After successfully compiling the project and deploying it to the npm registry, I encountered an issue when importing it into my client app. Specifi ...

Discover the files in the web directory using TypeScript

I am working on a TypeScript web application that has a specific folder structure. Here is how it looks: - assets |- a.png |- b.png |- c.png |- d.png |- ... - app.ts My question is: In the app.ts file, how can I programmatically list all the files wi ...

There has been a mistake: "Unable to locate a suitable differ supporting object '[object Object]' of type 'object'. NgFor is only able to bind to Iterables like Arrays."

Currently facing an issue: I am trying to extract the values of "place" using ngFor directive. Here's what I have implemented: .html <ng-container *ngFor="let se of List" Here is the JSON data: .json "place": [ { &qu ...

The options passed to createReadStream in TypeScript do not accept {start: 90, end: 99}

After updating to TypeScript 1.6.2, I encountered an issue with my call to createReadStream(). The problem arises because the type definition in node.d.ts does not recognize 'start' and 'end' in the options parameter. var st = fs.crea ...

What is the procedure for including a attribute in all sub-objects within a nested object using Typescript?

I need to create a function called addId that takes an object as input and returns the same object with an added property _id: string in every sub-object. Let's consider the input object constructed from the following class. class A { a: number b ...

A method for converting variables into various data types within a template

I have developed an Angular app where I have configured the following: "angularCompilerOptions": { "strictInjectionParameters": true, "fullTemplateTypeCheck": true, "strictTemplates": true } As a res ...

Convert an object to an array, but only if it is not already an array

If we need to iterate over either an Object or an Array of Objects, we can transform the Object into an array of one object and then iterate in our React App accordingly. Let's consider an example: // Returned value as object const zoo = { lion: &a ...

Troubleshooting Vue Unit Tests: Issue with Setting Input Values

I am currently utilizing Vue with typescript and making an effort to perform a unit test on the input value for a login page. The issue lies in the fact that after setting the input value, it does not return as expected – instead, it comes back empty ("" ...

Is there a method to indicate not using the watch feature through the command line in TSC?

Is it possible to disable the watch mode in the Typescript compiler cli through command line, instead of relying on the configurations from tsconfig.json? ...

When running npx ts-lint in a Docker environment, an error occurs stating that the module 'typescript' cannot be found

In the process of setting up a dockerized development environment for a node/typescript API project, I am aiming to have everything run within Docker without the need for node, npm, or modules installed on the host system. The main objective is to isolate ...

Why is the variable suddenly a number when I clearly defined it as a string?

Let's start with the following code snippet: let vAny: any = 10 let s1: string = vAny; console.log(typeof s1) In this scenario, I have explicitly defined that s1 should be a string. However, when inspecting the type of s1, it shows up as a number in ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Error in Angular: Trying to access the property 'id' of an undefined value

I am facing an issue with a div tag in my HTML file. The code snippet looks like this: <div *ngIf="chat.asReceiver.id != user?.id; else otherParty"> Unfortunately, it always returns the following error: ERROR TypeError: Cannot read propert ...

How to use Angular 8 Form Builder to upload an array of multiple images

My product form includes various fields like product name, description, and an array of images. Product Form Product Name - Product Description Product Purity - Product Commodity Images (Add) Checkbox 1 - Image 1 Checkbox 2 - Image 2 Checkbox 3 - ...

Remove all keys of type BaseType from objects that are children of BaseType

There are two types: BaseType and BabyType. export type BaseType = { id: string } export type BabyType = BaseType & { name: string }; In a generic layer where <T extends BaseType> is used, the item being dealt with is actually a 'B ...

Transforming jQuery library functions into TypeScript syntax

I have developed a directive using TypeScript. Here is an example of the code: 'use strict'; module App.Directives { interface IPageModal extends ng.IDirective { } interface IPageModalScope extends ng.IScope { //modal: any ...

Adding the unzip feature is not within my capabilities

I am a novice Japanese web developer. Unfortunately, my English skills are not great. I apologize for any inconvenience. I am interested in utilizing this specific module: https://www.npmjs.com/package/unzip To do so, I executed the following commands ...

What is the best way to find the average within different groups in a JavaScript Array?

I am currently working with the Angular JS framework and have a NodeJS array like this: var arr = [{"object":"Anguille","fct":"Type A","value":"2"},{"object":"Athérine"," ...