extended-enum icon indicating copy to clipboard operation
extended-enum copied to clipboard

Regard extended enum as exclusive union type of its instances

Open inhibitor1217 opened this issue 2 years ago • 1 comments

Native TypeScript enums are exclusive union of each members.

enum Fruit { Apple, Orange }

type T = Fruit.Apple & Type.Orange // never

This allows type interpretations in some use-cases to be useful:

declare const fruit: Fruit;

if (fruit === Fruit.Apple) { ... }
if (fruit === Fruit.Orange) { ... }
// now, compiler knows this code is not reachable
declare const fruit: Fruit;

switch (fruit) {
  case Fruit.Apple: { ..., break; }
  case Fruit.Orange: { ..., break; }
  // now, compiler knows this code is not reachable
}

Allow this functionality to extended enums, so that the following holds:

enum _Fruit { Apple, Orange }
const Fruit = extend<typeof _Fruit, _Fruit>(_Fruit);

type T = Fruit.Apple & Fruit.Orange; // never

Also, the extended enum class itself and the members should be type and value at the same time, like the native enum does.

type T = Fruit.Apple extends Fruit ? true : false // true

enum _Vegetable { Potato, Celery }
const Vegetable = extend<typeof _Vegetable, _Vegetable>(_Vegetable);

type U = Vegetable.Potato extends Fruit ? true : false // false

inhibitor1217 avatar Dec 05 '21 13:12 inhibitor1217

The exclusivity of instance types are implemented in #22. The next goal is to make the union of instance types to exhaustively define the whole type.

inhibitor1217 avatar Dec 11 '21 15:12 inhibitor1217