66

I currently have both an array of strings and a string literal union type containing the same strings:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = 'chair' | 'table' | 'lamp';

I need both in my application, but I am trying to keep my code DRY. So is there any way to infer one from the other?

I basically want to say something like type Furniture = [any string in furniture array], so there are no duplicate strings.

| improve this question | |
138

Update for TypeScript 3.0 :

With the use of generic rest parameters, there is a way to correctly infer string[] as a literal tuple type and then get the union type of the literals.

It goes like this:

const tuple = <T extends string[]>(...args: T) => args;
const furniture = tuple('chair', 'table', 'lamp');
type Furniture = typeof furniture[number];

More about generic rest parameters

Update for TypeScript 3.4:

TypeScript version 3.4 has introduced so-called const contexts, which is a way to declare a tuple type as immutable and get the narrow literal type directly (without the need to call a function like shown above).

With this new syntax, we get this nice concise solution:

const furniture = ['chair', 'table', 'lamp'] as const;
type Furniture = typeof furniture[number];

More about the new const contexts is found in this PR as well as in the release notes.

| improve this answer | |
  • 14
    Can I ask, what's the purpose of the index signature annotation [number]? Is that not inferred? – robC Jun 19 '19 at 15:45
  • @ggradnig Thanks for the answer! this feels like it was meant to take the place of string enums with reverse mappings, or am I wrong? are there other use cases for this? – Daniel Dubovski Jun 27 '19 at 14:07
  • 9
    The reason for the [number] is that without it typeof furniture would return an array type. With the index signature typeof furniture[number] is saying "the type of any valid numeric index in furniture, so you get a type that is a union of the values instead of an array type. – Jason Kohles May 19 at 16:43
  • 1
    Unfortunately, this only works with literal arrays. This will not work: const a = ["a", "b", "c"]; const b = a as const; - This will throw the following error: A 'const' assertions can only be applied to references to enum members, or string, number, boolean, array, or object literals. – Slavik Meltser Aug 3 at 9:52
11

This answer is out of date, see answer above.

The best available workaround:

const furnitureObj = { chair: 1, table: 1, lamp: 1 };
type Furniture = keyof typeof furnitureObj;
const furniture = Object.keys(furnitureObj) as Furniture[];

Ideally we could do this:

const furniture = ['chair', 'table', 'lamp'];
type Furniture = typeof furniture[number];

Unfortunately, today furniture is inferred as string[], which means Furniture is now also a string.

We can enforce the typing as a literal with a manual annotation, but it brings back the duplication:

const furniture = ["chair", "table", "lamp"] as ["chair", "table", "lamp"];
type Furniture = typeof furniture[number];

TypeScript issue #10195 tracks the ability to hint to TypeScript that the list should be inferred as a static tuple and not string[], so maybe in the future this will be possible.

| improve this answer | |
-1

The only adjustement I would suggest is to make the const guaranteed compatible with the type, like this:

type Furniture = 'chair' | 'table' | 'lamp';

const furniture: Furniture[] = ['chair', 'table', 'lamp'];

This will give you a warning should you make a spelling error in the array, or add an unknown item:

// Warning: Type 'unknown' is not assignable to furniture
const furniture: Furniture[] = ['chair', 'table', 'lamp', 'unknown'];

The only case this wouldn't help you with is where the array didn't contain one of the values.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.