Is it possible to create a class object with properties directly from the constructor, without needing to cast a custom constructor signature

class __Constants__ {
  [key: string]: string;
  constructor(values: string[]) {
    values.forEach((key) => {
      this[key] = key;
    });
  }
}

const Constants = __Constants__ as {
  new <T extends readonly string[]>(values: T): { [k in T[number]]: k };
};

const __colors__ = ["BLUE", "GREEN"] as const;

const Colors = new Constants(__colors__);
// const Colors: {
//   BLUE: "BLUE",
//   GREEN: "GREEN",
// }

Is there a way to define the __Constants__ class to have the same output type as the cast, without needing to modify the custom constructor signature?

Note that I am currently working on transitioning an old JavaScript codebase to TypeScript and aiming to minimize alterations to the original JS code. The actual Constants class is more complex, but here I've simplified the issue I'm encountering.

Answer №1

Here is how it operates:

const Constants = class {
  [key: string]: string;
  constructor(values: string[]) {
    values.forEach((key) => {
      this[key] = key;
    });
  }
} as {
  new <T extends readonly string[]>(values: T): { [k in T[number]]: k };
};


const __colors__ = ["BLUE", "GREEN"] as const;

const Colors = new Constants(__colors__);

TypeScript playground

This script utilizes what are known as "Class expressions"


UPDATE: I experimented with another approach. Instead of a class, why not use a function like this:

function Constants<T extends readonly string[]>(values: T): { [k in T[number]]: k } {
  const obj: any = {};
  values.forEach((key) => {
    obj[key] = key;
  });
  return obj;
}

TypeScript playground

Remember to invoke it as a function rather than creating an instance of the class:

const __colors__ = ["BLUE", "GREEN"] as const;

const Colors = Constants(__colors__); // avoid using "new" here

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

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

Tips for manually inputting dates in Primeng Calendar Datepicker with the slash "/" symbol

I need assistance with adding slashes to manual input when using the primeng Calendar component. <p-calendar [monthNavigator]="true" [yearNavigator]="true" yearRange="1950:2021" ngModel [required]="tru ...

What strategies can I use to address the issue of requiring a type before it has been defined?

Encountered an intriguing challenge. Here are the types I'm working with: export interface QuestionPrimative { question : string; id : string; name : string; formctrl? : string; formgrp? : string; lowEx ...

Creating an Inner Join Query Using TypeORM's QueryBuilder: A Step-by-Step Guide

Hello there! I'm new to TypeORM and haven't had much experience with ORM. I'm finding it a bit challenging to grasp the documentation and examples available online. My main goal is to utilize the TypeORM QueryBuilder in order to create this ...

Tips for specifying the type when utilizing the spread operator to pass props

type TypeData = { data: { id: string; class: string; name: string; country: string; ew_get_url: string; ew_post_url: string; rocket_id: string; pages: { landing: { h1: string; h2: string; } ...

Troubleshooting fastify library errors related to ajv validation

Every time I try to build my TypeScript code, I encounter these errors: The following errors are showing up in my TypeScript code: 1. node_modules/@fastify/ajv-compiler/types/index.d.ts(1,10): error TS2305: Module 'ajv' has no exported member ...

Packaging a NodeJS project in Visual Studio - A step-by-step guide to creating and setting up an N

In my VS2013 solution, I have a combination of NodeJS (using TypeScript) and C# class library projects connected by EdgeJS. Among the NodeJS projects, one serves as a library for a RabbitMQ bus implementation, while two are applications meant to be hosted ...

My customized mat-error seems to be malfunctioning. Does anyone have any insight as to why?

Encountering an issue where the mat-error is not functioning as intended. A custom component was created to manage errors, but it is not behaving correctly upon rendering. Here is the relevant page code: <mat-form-field appearance="outline"> < ...

Is the naming convention for parameterized types (T, U, V, W) in Generics adhered to by Typescript?

Is TypeScript following the same naming convention for parameterized types as other languages like C++ and Java, using T,U,V,W, or is there a mixed usage of conventions? In the TS 2.8 release notes, we see examples like: type ReturnType<T> = T exten ...

Redux-toolkit payload does not recognize the specified type

While working on my project, I encountered an issue when using redux-toolkit. I have created the following reducer: setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => { let gridPolygonsData: GridPolygonsData; const { ...

The struggle of implementing useReducer and Context in TypeScript: A type error saga

Currently attempting to implement Auth using useReducer and Context in a React application, but encountering a type error with the following code snippet: <UserDispatchContext.Provider value={dispatch}> The error message reads as follows: Type &apos ...

RxJS: Transforming an Observable array prior to subscribing

I am retrieving data (students through getStudents()) from an API that returns an Observable. Within this result, I need to obtain data from two different tables and merge the information. Below are my simplified interfaces: export interface student Stude ...

Steps for referencing a custom JavaScript file instead of the default one:

Currently, I am utilizing webpack and typescript in my single page application in combination with the oidc-client npm package. The structure of the oidc-client package that I am working with is as follows: oidc-client.d.ts oidc-client.js oidc-client.rs ...

Exploring the functionality of custom hooks and context in asynchronous methods using React Testing Library

I'm currently testing a hook that utilizes a context underneath for functionality This is how the hook is structured: const useConfirmation = () => { const { openDialog } = useContext(ConfirmationContext); const getConfirmation = ({ ...option ...

When you use array[index] in a Reduce function, the error message "Property 'value' is not defined in type 'A| B| C|D'" might be displayed

Recently, I delved deep into TypeScript and faced a challenge while utilizing Promise.allSettled. My objective is to concurrently fetch multiple weather data components (such as hourly forecast, daily forecast, air pollution, UV index, and current weather ...

tips for concealing a row in the mui data grid

I am working on a data grid using MUI and I have a specific requirement to hide certain rows based on a condition in one of the columns. The issue is that while there are props available for hiding columns, such as hide there doesn't seem to be an eq ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...

Key factors to keep in mind when comparing JavaScript dates: months

Check the dates and determine if the enddate refers to the following month by returning a boolean value. Example startdate = January 15, 2020 enddate = February 02, 2020 Output : enddate is a future month startdate = January 15, 2020 enddate = January 2 ...

Transforming Excel data into JSON format using ReactJS

Currently, I am in the process of converting an imported Excel file to JSON within ReactJS. While attempting to achieve this task, I have encountered some challenges using the npm XLSX package to convert the Excel data into the required JSON format. Any as ...

The expansion feature of PrimeNG Turbotable

I'm currently facing an issue with the Primeng Turbotable where I am unable to expand all rows by default. You can find a code example of my problem at this link. I have already tried implementing the solution provided in this example, but unfortuna ...