typescript - Ways to get string literal type of array values without enum overhead -


in project need number of string literal types , arrays of allowed values variuos tasks typeguards.

this have:

type animal = 'cat' | 'dog' | 'rabbit' | 'snake' const animals: animal[] = ['cat', 'dog', 'rabbit', 'snake'] 

it works, requires list keys several times in source code.

another way use enums suggested in get array of string literal type values creates overhead in runtime compiled code enum bigger array.

i found way have no runtime overhead, i'm not sure if work in future, may bug.

const notwidened = <t extends string>(val: t[]) => val  const animals = notwidened(['cat', 'dog', 'rabbit', 'snake']) type animal = typeof animals[0] 

so question if it's safe use snippet or going break in future. there better way both literal string type , array without duplication.

i can't find piece of documentation @ moment, notwidened() function works fine , not bug. typescript infer string literals generic type variables if constrain type parameter string or subtype of string. <t extends keyof u>, <t extends string>, <t extends 'a'|'b'>, etc. infer string literals t. (you can infer number or boolean literals if constrain t similarly).

so code fine far can see; thing might differently is

type animal = (typeof animals)[number] 

instead of

type animal = typeof animals[0] 

since 0th element of animals 'cat', though you've told typescript 'cat'|'dog'|.... yours fine, though.

as commented above, if want typescript consider animals tuple animals[0] of type 'cat', , animals[1] of type 'dog', etc., can use function tuple() in tuple.ts:

const animals = tuple('cat', 'dog', 'rabbit', 'snake'); type animal = (typeof animals)[number];  // union type 

which might come in handy you.


tl;dr: 👍 code fine.

hope helps; luck!


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -