Dynamic property Key in TypeScript

Imagine receiving data from a search engine in the following format:

const resultDe = { details_de: "Ein paar Informationen", foo_de:{bar:"barDe"}, code: "1C60" }
const resultEn = { details_en: "Some information", foo_en:{bar:"barEn"} code: "1C60" }

You may be aware of the property names, but some properties have language-specific suffixes like _de or _en. Is there a way to define such data types using TypeScript?

For instance, can we do something like this:

type Result = {
  `details_${lang}`: string;
}

Answer №1

If you're looking to implement dynamic types in TypeScript, you can utilize mapped types:

type Language = 'de' | 'en'
type Details = {
    [Key in `details_${Language}`]: string
}

const details: Details = { details_en: 'foo', details_de: 'bar' }

Answer №2

Utilize template literals in Typescript to define types like this:

type LanguageResult<LangCode extends string> = Record<`details_${LangCode}`, string>;

const enResults: LanguageResult<'en'> = {
  details_en: 'test',
};

const enResults: LanguageResult<'de'> = {
  details_en: 'test', // <- Error
};

TypeScript Playground


If the specific strings are unknown, use the broadest type - string - to allow any codes. Example:

type LanguageResult<LangCode extends string = string> = Record<`details_${LangCode}`, string>;

const anyResults: LanguageResult = {
  details_en: 'test',
  details_de: 'test',
};

TypeScript Playground

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

Leveraging interfaces with the logical OR operator

Imagine a scenario where we have a slider component with an Input that can accept either Products or Teasers. public productsWithTeasers: (Product | Teaser)[]; When attempting to iterate through this array, an error is thrown in VS Code. <div *ngFor= ...

Protected class, yet not transferable

My output varies based on the type of input provided. I have a custom guard in place to protect the input, but I'm still having trouble assigning it to the declared output: type InputType<Sub extends SubType> = { a: Sub, b: string } type SubTyp ...

How to Use a For Each Loop with Google Maps DrawingManager to Create Polygons?

My Ionic 4 Application using Angular 8 incorporates a google maps component where I need to draw and edit multiple polygons, eventually saving their vertices in a database. Hard coding some polygons is easy with getPath() or getPaths(), but I'm utiliz ...

Issues with type errors in authentication wrapper for getServerSideProps

While working on implementing an auth wrapper for getServerSideProps in Next.js, I encountered some type errors within the hook and on the pages that require it. Below is the code for the wrapper along with the TypeScript error messages. It's importan ...

Efficiently process and handle the responses from Promise.all for every API call, then save the retrieved data

Currently, I am passing three API calls to Promise.all. Each API call requires a separate error handler and data storage in its own corresponding object. If I pass test4 to Promise.all, how can I automatically generate its own error and store the data in ...

Create a combined string from a structure resembling a tree

In my web application, I have a type that defines the different routes available: interface IRoute { readonly path: string, readonly children?: IRoute[] } I want to create a union type containing all possible paths based on an IRoute object. Let&apos ...

Utilizing conditional types for type narrowing within a function's body: A comprehensive guide

I created a conditional type in my code that constrains the second argument of my class constructor based on the type of the first argument. Although the type checker correctly limits what I can pass to the constructor, I am struggling to get the compiler ...

To switch to desktop mode, double click; for mobile view, just tap once

I am looking to implement 2 different gestures for a specific feature in my application. Ideally, I want users to be able to double click on a card to open it in desktop view, but if they are using a phone, a single tap should suffice. How can I achieve th ...

Using Typescript: Defining a function parameter that can be either of two interfaces

While browsing through this specific question, I noticed that it was somewhat related to my current issue, although there were notable differences. In my scenario, I have a function named parseScanResults which accepts an object as its argument. This obje ...

Create Angular file structures effortlessly using a tool similar to Rails scaffold

Is there a code generator in Angular similar to RoR's rails scaffold? I am looking to run a specific command and receive the following files, such as: *.component.html *.component.sass *.component.ts *.module.ts. ...

I'm currently endeavoring to integrate SignalR into my Vue project and encountering an issue

Currently, I am working on a project using Vue with TypeScript and I am interested in integrating SignalR. I have thoroughly studied the documentation provided by '@dreamonkey/vue-signalr' on how to utilize SignalR. import { VueSignalR } from &ap ...

What is the process for importing the TokenExpiredError that is thrown by the verify function in jsonwebtoken?

Is there a way to determine if an Error object thrown by the jwt.verify function in the jsonwebtoken library is of type TokenExpiredError using Typescript's instanceof? For example: import jwt from "jsonwebtoken"; function someFunction() { try { ...

Tips for leveraging the functions service in Next.js for better code reusability

I am just starting to learn Next.js and I have a preference for organizing my API functions in a separate folder called services. I attempted to implement some code based on this topic but unfortunately, it did not work as expected. It seems like my api fu ...

I'm having trouble with the calculator, unable to identify the issue (Typescript)

I'm struggling with programming a calculator for my class. I followed the instructions from our lesson, but it's not functioning properly and I can't pinpoint the issue. I just need a hint on where the problem might be located. The calculat ...

Defining a type with limited knowledge: if you only have one key in the object

Attempting to establish a type for an object Consider the following object structure: { a: 123, b: "hello", c: { d:"world" } } The keys present in the object are unknown. To define its type, I would use Record<st ...

The cucumber_report.json file will not update to reflect the most recent test steps

I have encountered an issue with the cucumber_reporter.json file not overwriting under the reports/html folder in my framework. To address this, I made changes to the cucumberOpts option within my config.ts file. By modifying the format setting to "json:./ ...

A unique column in the Foundry system that utilizes function-backed technology to calculate the monthly usage of engines over a

In my dataset of ‘Engine Hours’, I have the following information: Engine# Date Recorded Hours ABC123 Jan 21, 2024 9,171 ABC123 Dec 13, 2023 9,009 ABC123 Oct 6, 2023 8,936 XYZ456 Jan 8, 2024 5,543 XYZ456 Nov 1, 2023 4,998 XYZ456 Oct 1 ...

Challenges encountered while using TypeScript to implement the CSS breakpoint mixin

I attempted to replicate the breakpoint mixin functionality described at using TypeScript, but I am having trouble correctly typing the function. import { css } from 'styled-components'; import { breakpoints } from './_variables'; exp ...

My worker threads seem to be flying under the radar

Currently, I am working on implementing worker threads into my Node.js/Typescript application. I have made significant progress, but it appears that my worker threads are not being executed as expected. Despite adding loggers inside the function intended f ...

Is it possible to utilize instanceof to verify whether a certain variable is of a class constructor type in TypeScript?

I am currently facing an issue with a function that takes a constructor as a parameter and creates an instance based on that constructor. When attempting to check the type of the constructor, I encountered an error. Below are some snippets of code that I ...