What is the method for generating a data type from an array of strings using TypeScript?

Is there a more efficient way to create a TypeScript type based on an array of strings without duplicating values in an Enum declaration? I am using version 2.6.2 and have a long array of colors that I want to convert into a type.

Here is what I envision:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
export type Color = convertStringArrayToType(colors);

The existing solution, as described here, does work but seems a bit hacky:

/** Utility function to create a K:V from a list of strings */
function strEnum<T extends string>(o: Array<T>): {[K in T]: K} {
  return o.reduce((res, key) => {
    res[key] = key;
    return res;
  }, Object.create(null));
}

/**
  * Sample create a string enum
  */

/** Create a K:V */
const Direction = strEnum([
  'North',
  'South',
  'East',
  'West'
])
/** Create a Type */
type Direction = keyof typeof Direction;

Answer №1

Beginning with Typescript version 3.4, developers can utilize the as const feature to create a union type from an array in the following manner:

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] as const;
export type Color = typeof colors[number]; // 'red'|'orange'|'yellow'|'green'|'blue'|'indigo'|'violet'

Answer №2

To expand on @guido-dizioli's response, you have the option to develop a reusable function for generating a dynamic type while still taking advantage of IntelliSense:

https://i.stack.imgur.com/JSnpJ.png One thing to note is that the user must specify the array using as const:

const properties = [
    "initialize", 
    "processData", 
    "executeAction", 
    "fetchResult"
] as const;

function createObject<T extends readonly string[]>(steps: T): Record<T[number], object> {
    const typed = {} as Record<string, string>;
    steps.forEach(step => typed[step] = step);
    return typed as unknown as Record<T[number], object>;
}

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

Can you point me to the source of definition for Vue 2's ComponentDefinition and ComponentConstructor types?

I am struggling to add a dynamic Vue 2 component with correct typing in TypeScript. The documentation clearly mentions that the is attribute accepts values of type string | ComponentDefinition | ComponentConstructor, but I cannot locate these custom types ...

Tips for updating ion-select option to correspond with the object by utilizing the object's identifier as the value

In my code, I have a select element that looks like this. <ion-select formControlName="location" (click)="clearSectionAndTask()"> <ion-select-option *ngFor="let location of locations" value="{{location.locationId}}"> ...

Customize your Joi message using the .or() method

I'm attempting to personalize a message for the .or() function in Joi, similar to this: https://i.stack.imgur.com/68dKx.png The default message from Joi is as follows: Validation Error: "value" must contain at least one of [optionOne, optionTwo] ...

Substitute all attributes of objects with a different designation

I need to update all object properties from label to text. Given: [ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", &q ...

Guidelines for Nestjs class-validator exception - implementing metadata information for @IsNotIn validator error handling

I have a NestJs data transfer object (dto) structured like this import { IsEmail, IsNotEmpty, IsNotIn } from 'class-validator'; import { AppService } from './app.service'; const restrictedNames = ['Name Inc', 'Acme Inc&ap ...

Tips for telling the difference between typescript Index signatures and JavaScript computed property names

ngOnChanges(changes: {[paramName: string]: SimpleChange}): void { console.log('Any modifications involved', changes); } I'm scratching my head over the purpose of 'changes: {[propName: string]: SimpleChange}'. Can someone cl ...

Typescript offers a feature where we can return the proper type from a generic function that is constrained by a lookup type,

Imagine we have the following function implementation: type Action = 'GREET' |'ASK' function getUnion<T extends Action>(action: T) { switch (action) { case 'GREET': return {hello: &a ...

In what way can TS uniquely handle each element of an array as the key of an object?

I am struggling with an object that I need to have keys representing every item in the array, each linked to a value of any. Can anyone provide guidance on how to achieve this? Unfortunately, I couldn't find a solution. Here is an example for refere ...

NextJs Route Groups are causing issues as they do not properly exclude themselves from the app's layout.tsx

As far as I know, the layout.tsx in the app directory serves as the root layout. To customize the layout structure for specific segments, you can use Route Groups. More information can be found here. In this setup, any page.tsx file inside a directory nam ...

Require that the parent FormGroup is marked as invalid unless all nested FormGroups are deemed valid - Implementing a custom

Currently, I am working on an Angular 7 project that involves dynamically generating forms. The structure consists of a parent FormGroup with nested FormGroups of different types. My goal is to have the parentForm marked as invalid until all of the nested ...

Data is not displaying correctly in the Angular Material Table

I'm currently trying to build a mat table based on an online tutorial, but I'm facing a problem where the table appears empty even though I have hard coded data. As someone new to Angular and HTML/CSS, I'm struggling to understand why the ma ...

Converting Typescript library into a standalone global JavaScript file

Currently working on developing a Typescript library that follows this structure: https://i.stack.imgur.com/YyCHk.jpg This includes the following files: restApi.class.ts import { restApiOptions } from '../models/rest.options.model'; import { ...

Tips for creating a seamless merge from background color to a pristine white hue

Seeking a seamless transition from the background color to white at the top and bottom of the box, similar to the example screenshot. Current look: The top and bottom of the box are filled with the background color until the edge https://i.stack.imgur.com ...

The type '{} is not compatible with the type 'IProps'

In my current project, I am utilizing React alongside Formik and TypeScript. The code snippet below demonstrates my usage of the withFormik Higher Order Component (HOC) in my forms: import React from 'react'; // Libraries import........ import { ...

Windows authentication login only appears in Chrome after opening the developer tools

My current issue involves a React app that needs to authenticate against a windows auth server. To achieve this, I'm hitting an endpoint to fetch user details with the credentials included in the header. As per my understanding, this should trigger th ...

Stop extra properties from being added to the return type of a callback function in TypeScript

Imagine having an interface called Foo and a function named bar that accepts a callback returning a Foo. interface Foo { foo: string; } function bar(callback: () => Foo): Foo { return callback(); } Upon calling this function, if additional pr ...

`Is there a way to repurpose generic type?`

For instance, I have a STRING type that is used in both the test and test2 functions within the test function. My code looks like this: type STRING = string const test = <A = STRING>() => { test2<A>("0") } const test2 = <B& ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Using TypeScript to return an empty promise with specified types

Here is my function signature: const getJobsForDate = async (selectedDate: string): Promise<Job[]> I retrieve the data from the database and return a promise. If the parameter selectedDate === "", I aim to return an empty Promise<Job[] ...

What is the reason behind being able to assign unidentified properties to a literal object in TypeScript?

type ExpectedType = Array<{ name: number, gender?: string }> function go1(p: ExpectedType) { } function f() { const a = [{name: 1, age: 2}] go1(a) // no error shown go1([{name: 1, age: 2}]) // error displayed ...