Can dynamic string types be declared in Typescript?

Let's consider the following scenario:

export enum EEnv { devint, qa1 };
export type TEnv = keyof typeof EEnv;
export const env:Record<TEnv, {something:number}> = {
  devint: {
    something: 1,
  },
  qa1: {
    something: 1,
  },
}

Now, I aim to generate a dynamic object based on the env object, as demonstrated below:

export const SAVE_TOKEN: Record<TEnv, string> = {
  devint: "SAVE_TOKEN/devint", // derived from "env" key
  qa1: "SAVE_TOKEN/qa1", // derived from "env" key
}

Is it possible to define a type in such a way that it would be "SAVE_TOKEN/"+TEnv instead of just a plain string?

Answer №1

For those still searching for updates, the feature mentioned will now be included in version 4.1 of TypeScript. You can find more information at TypeScript#40336.

export type SaveTokenNamespace<K extends string> = { [T in K]: `SAVE_TOKEN/${T}` };

export function makeNamespace<K extends TEnv>(env: Record<K, unknown>): SaveTokenNamespace<K> {
  return Object.keys(env).reduce((ns, k) => ({ ...ns, [k]: `SAVE_TOKEN/${k}` }), {} as SaveTokenNamespace<K>);
}

console.log(makeNamespace(env));
const envNamespace = makeNamespace(env);
const test1: 'SAVE_TOKEN/qa1' = envNamespace.qa1; // Ok!
const test2: 'SAVE_TOKEN/notqa1' = envNamespace.qa1; // Error: Type '"SAVE_TOKEN/qa1"' is not assignable to type '"SAVE_TOKEN/notqa1"'.

Experiment with it on the TypeScript playground


There are several well-known open proposals/requests such as Regex-validated string type: TypeScript#6579 and TypeScript#12754. This includes a specific mention regarding this use case, but as of version 3.5.1, the answer remains negative.

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

Syncing data between local storage and a remote server using Ionic5 provider

I've been considering implementing a data provider that could store a duplicate of the backend data locally for quick access. I believe this concept is referred to as mirroring or something similar. Nevertheless, it must be synchronized and updated r ...

Tips for making the onChange event of the AntDesign Cascader component functional

Having an issue with utilizing the Cascader component from AntDesign and managing its values upon change. The error arises when attempting to assign an onChange function to the onChange property of the component. Referencing the code snippet extracted dire ...

Updating from version 1.8.10 to 2.9.2 and encountering a build error in version 4.6.4

I currently have an angular application that is using typescript version 1.8.10 and everything is running smoothly. However, I am interested in upgrading the typescript version to 2.9.2. After making this change in my package.json file and running npm inst ...

When using ngx-slider in Angular, it unexpectedly fires off when scrolling on mobile devices

I am currently developing a survey application that utilizes ngx-sliders. However, I have encountered an issue on mobile devices where users unintentionally trigger the slider while scrolling through rows of slider questions, resulting in unintended change ...

utilizing $inject method along with supplementary constructor parameters

After referencing the answer found here: Upon implementing the $inject syntax, my controller code appears as follows: class MyCtrl { public static $inject: string[] = ['$scope']; constructor($scope){ // implementation } } // register ...

Module not found

Hey everyone, I recently updated my project to node version v14.18.0, but now I'm encountering a "module not found" issue (see screenshot below). Any suggestions on how to resolve this? https://i.stack.imgur.com/k0u82.png ...

Developing a TypeScript NodeJS module

I've been working on creating a Node module using TypeScript, and here is my progress so far: MysqlMapper.ts export class MysqlMapper{ private _config: Mysql.IConnectionConfig; private openConnection(): Mysql.IConnection{ ... } ...

Utilizing Angular 4 with Ahead-Of-Time compilation in combination with Electron, as well as

I am new to Angular/Typescript and currently developing a cross-platform Desktop application with Electron and Angular 4. My current challenge involves using a Service in different components, but I need this service to be loaded from a separate file based ...

Commit to calculating the total sum of each element using AngularJS

Trying to implement a like counter using Facebook's GRAPH API. I have a list of object IDs and for each ID, I make an API call to retrieve the number of likes and calculate a total. The issue arises as the API call returns a promise, causing only one ...

How to add an item to an array in JavaScript without specifying a key

Is there a way to push an object into a JavaScript array without adding extra keys like 0, 1, 2, etc.? Currently, when I push my object into the array, it automatically adds these numeric keys. Below is the code snippet that I have tried: let newArr = []; ...

I am interested in monitoring for any alterations to the @input Object

I've been attempting to detect any changes on the 'draft' Object within the parent component, however ngOnChange() does not seem to be triggering. I have included my code below, but it doesn't even reach the debugger: @Input() draft: ...

I'm wondering why Jest is taking 10 seconds to run just two simple TypeScript tests. How can I figure out the cause of this sluggish performance?

I've been experimenting with Jest to execute some TypeScript tests, but I've noticed that it's running quite slow. It takes around 10 seconds to complete the following tests: import "jest" test("good", () => { expec ...

The const keyword is not automatically inferred as a const when using conditional types for generic type parameters

Within Typescript, the const modifier can be applied to function type parameters. This ensures that the inferred type matches the literal received with as const. function identity<const T>(a: T){ return a } For example, when using identity({ a: 4 ...

Utilizing MakeStyles from Material UI to add styling to a nested element

I was pondering the possibility of applying a style specifically to a child element using MakesStyles. For instance, in a typical HTML/CSS project: <div className="parent"> <h1>Title!</h1> </div> .parent h1 { color: # ...

Determine the return type of a function based on a key parameter in an interface

Here is an example of a specific interface: interface Elements { divContainer: HTMLDivElement; inputUpload: HTMLInputElement; } My goal is to create a function that can retrieve elements based on their names: getElement(name: keyof Elements): Elemen ...

Determine data types for functions in individual files when using ElysiaJS

Currently, I am utilizing ElysiaJS to establish an API. The code can be found in the following open-source repository here. In my setup, there are three essential files: auth.routes.ts, auth.handlers.ts, and auth.dto.ts. The routes file contains the path, ...

Error encountered in Angular 7.2.0: Attempting to assign a value of type 'string' to a variable of type 'RunGuardsAndResolvers' is not allowed

Encountering an issue with Angular compiler-cli v.7.2.0: Error message: Types of property 'runGuardsAndResolvers' are incompatible. Type 'string' is not assignable to type 'RunGuardsAndResolvers' This error occurs when try ...

Having trouble with the removeEventListener OnDestroy not functioning properly in Angular 6 using Javascript?

I have been experimenting with using the removeEventListener function in my Angular component. I came across a helpful discussion on this topic: Javascript removeEventListener not working ... ngOnInit() { document.addEventListener('v ...

What is the best way to ensure that each service call to my controller is completed before proceeding to the next one within a loop in Angular?

Calling an Angular service can be done like this: this.webService.add(id) .subscribe(result => { // perform required actions }, error => { // handle errors }); // Service Definition add(id: number): Observable < any > { retu ...

What could be causing Typescript to inaccurately infer the type of an array element?

My issue revolves around the object named RollingStockSelectorParams, which includes arrays. I am attempting to have TypeScript automatically determine the type of elements within the specified array additionalRsParams[title]. The main question: why does ...