Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a type from a string array in TypeScript?

What is the best way of making a TypeScript type based on an array of strings? I am on version 2.6.2. The array is long and I do not want to repeat myself by duplicating the string values in an Enum declaration.

What I want to do is something like this:

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

The following solution (source) works fine, but feels 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;
like image 478
Stewart Avatar asked Jul 25 '18 14:07

Stewart


People also ask

How do you give an array a type?

To create an array type you can use Array<Type> type where Type is the type of elements in the array. For example, to create a type for an array of numbers you use Array<number> . You can put any type within Array<Type> .

How do you declare an array of any type in TypeScript?

In TypeScript, an array is an ordered list of values. An array can store a mixed type of values. To declare an array of a specific type, you use the let arr: type[] syntax.

How do you check the type of an element in an array?

Answer: Use the Array. isArray() Method isArray() method to check whether an object (or a variable) is an array or not. This method returns true if the value is an array; otherwise returns false .


1 Answers

Since Typescript 3.4, you could use as const and generate a union type from an array as follows

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'] as const;
export type Color = typeof colors[number]; // 'red'|'orange'|'yellow'|'green'|'blue'|'indigo'|'violet'
like image 171
Guido Dizioli Avatar answered Sep 22 '22 01:09

Guido Dizioli