Igor Zvyagin
Igor Zvyagin

Reputation: 474

How get enum-like behavior from array? Typescript

I have array:

const someArray = ['one', 'two', 'three'];

and I have type:

type SomeType = 'one' | 'two' | 'three';

How can I get SomeType from someArray?

Upvotes: 0

Views: 105

Answers (4)

Igor Zvyagin
Igor Zvyagin

Reputation: 474

I found an even simpler solution.

const someArray = ['one', 'two', 'three'] as const;
                                       /* ^------- IMPORTANT!
                                          otherwise it'll just be `string[]` */

type SomeType = typeof someArray[number];  // 'one' | 'two' | 'three'

Upvotes: 1

hackape
hackape

Reputation: 19957

You can, at the cost that you have to apply as const assertion to someArray.

const someArray = ['one', 'two', 'three'] as const;
                                       /* ^------- IMPORTANT!
                                          otherwise it'll just be `string[]` */

type GetItem<T> = T extends ReadonlyArray<infer I> ? I : never;

type SomeType = GetItem<typeof someArray>;  // 'one' | 'two' | 'three'

Upvotes: 3

Lodewijk Bogaards
Lodewijk Bogaards

Reputation: 19987

You can not, because TypeScript is not a dependently-typed language.

TypeScript, like almost any other well known statically typed language in existence at the moment, can create types for values, but not create types from values.

So you can create a type for your values:

const someArray: SomeType[] = ['one', 'two', 'three'];

but you can not create a type from your values:

type SomeType = infer T for someArray[T] // invented syntax

Only dependently typed languages can do this. Unfortunately this is not yet mainstream. Give it another decade though and you'll be hearing more about this.

Probably this does not mean you are stuck though. Over time I've had very few times where I could absolutely not get to the type just because the language was not dependently typed. You should try to ask another question and might get a satisfactory answer. There are ways for example to have types available during runtime, like with https://github.com/gcanti/io-ts.

Upvotes: 1

zht
zht

Reputation: 7

by 'filter' to ergodic return satisfy condition‘s element

Upvotes: -1

Related Questions