0

I have defined the following type:

type UserConfigCategories = 'tables-config' | 'link-config' | 'general-config';

however this type can grow and I do not want to have to update it. Is it possible to create this type dynamically from an array, for example?

edu
  • 434
  • 1
  • 8
  • 17
  • That really depends on what you mean by "dynamically" – jcalz Jun 20 '19 at 19:08
  • 1
    Possible duplicate of [Typescript derive union type from tuple/array values](https://stackoverflow.com/questions/45251664/typescript-derive-union-type-from-tuple-array-values) – jcalz Jun 20 '19 at 19:10
  • Create it with code by iterating an array and not defining it literally – edu Jun 20 '19 at 19:10
  • 2
    Possible duplicate of [Typescript derive union type from tuple/array values](https://stackoverflow.com/questions/45251664/typescript-derive-union-type-from-tuple-array-values) – Shaun Luttin Jun 21 '19 at 01:16

1 Answers1

4

If the array defining the categories is a literal somewhere in your source you can infer the type from the values with as const added in 3.4.

const CONFIG_CATEGORIES = ['tables-config', 'link-config', 'general-config'] as const;
type UserConfigCategories = (typeof CONFIG_CATEGORIES)[number]

const u: UserConfigCategories = 'tables-config';
const v: UserConfigCategories = 'bad-name'; // Type '"bad-name"' is not assignable to type 
                                            // '"tables-config" | "link-config" | "general-config"'.
SpencerPark
  • 3,298
  • 1
  • 15
  • 27
  • I appreciate your answer, but the problem is that, nowhere in the code the categories is a literal. – edu Jun 20 '19 at 19:25
  • 3
    Ah I see, in that case it is not possible. Consider the fact that types are checked at compile time which means typescript needs the information before any code runs. If the values are truly dynamic as you say, `string` is the only thing that can type it without nominal typing in the language. – SpencerPark Jun 20 '19 at 19:35
  • I get it. It makes a lot of sense. Thank you very much for your clear response. – edu Jun 20 '19 at 19:40
  • It should be possible. This is what generics are for. – Ozymandias Jan 25 '21 at 23:33