Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an enum inside enum in typescript?

enum KINDS {
  STATIC = 1,
  FIELD,
  ARG,
  VAR
}

enum ALL_KINDS {
  STATIC = 1,
  FIELD,
  ARG,
  VAR,
  NONE
}

How can I reuse the first enum inside the second one?

like image 564
Henok Tesfaye Avatar asked Sep 29 '19 19:09

Henok Tesfaye


People also ask

Can enum extend another enum TypeScript?

The short answer is no, you can't extend enums because TypeScript offers no language feature to extend them.

Can we define enum inside a enum?

We can an enumeration inside a class. But, we cannot define an enum inside a method.

Should you use enums in TypeScript?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Does TypeScript support heterogeneous enum?

There are three types of TypeScript enums, namely: Numeric enums. String enums. Heterogeneous enums.


1 Answers

AFAIK, extending enums is under consideration, in the meantime you can use const objects instead:

const KINDS = <const>{
  STATIC: 1,
  FIELD: 2,
  ARG: 3,
  VAR: 4
};

const ALL_KINDS = <const>{ ...KINDS, NONE: 5 };

There are also other workarounds in the above thread.

If you want this type to be checked, note that from the type perspective, a numeric enum is equivalent to number:

enum KINDS {
  STATIC,
  FIELD,
  ARG,
  VAR
}

declare function func(name: string, type: string, kind: KINDS): any;

func('foo', 'bar', KINDS.ARG); // compiles
func('foo', 'bar', 99); // compiles too (?)

If you use an object as suggested above, you can also enforce strict type checking by creating a type for all possible values of that object:

const KINDS = <const>{
  STATIC: 1,
  FIELD: 2,
  ARG: 3,
  VAR: 4
};

type KIND_VALUE = typeof KINDS[keyof typeof KINDS]

declare function define(name: string, type: string, kind: KIND_VALUE): any;

define('foo', 'bar', KINDS.ARG); // compiles
define('foo', 'bar', 99); // doesn't compile

This is a bit more verbose, but then you have your type actually checked.

like image 110
georg Avatar answered Sep 29 '22 01:09

georg