Skip to content

Commit

Permalink
Merge pull request #523 from UppaJung/patch-4
Browse files Browse the repository at this point in the history
Fix Nominal Typing for TypeScript 3.6.2 by forcing enums to be string enums
  • Loading branch information
basarat authored Sep 16, 2019
2 parents 355290d + 01df80f commit 4ddda9b
Showing 1 changed file with 4 additions and 2 deletions.
6 changes: 4 additions & 2 deletions docs/tips/nominalTyping.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ This is demonstrated below where the structure of the types is just a string:

```ts
// FOO
enum FooIdBrand {}
enum FooIdBrand { _ = "" };
type FooId = FooIdBrand & string;

// BAR
enum BarIdBrand {}
enum BarIdBrand { _ = "" };
type BarId = BarIdBrand & string;

/**
Expand All @@ -72,6 +72,8 @@ str = fooId;
str = barId;
```

Note how the brand enums, ``FooIdBrand`` and ``BarIdBrand`` above, each have single member (_) that maps to the empty string, as specified by ``{ _ = "" }``. This forces TypeeScript to infer that these are string-based enums, with values of type ``string``, and not enums with values of type ``number``. This is necessary because TypeScript infers an empty enum (``{}``) to be a numeric enum, and as of TypeScript 3.6.2 the intersection of a numeric ``enum`` and ``string`` is ``never``.

## Using Interfaces

Because `numbers` are type compatible with `enum`s the previous technique cannot be used for them. Instead we can use interfaces to break the structural compatibility. This method is still used by the TypeScript compiler team, so worth mentioning. Using `_` prefix and a `Brand` suffix is a convention I strongly recommend (and [the one followed by the TypeScript team](https://github.com/Microsoft/TypeScript/blob/7b48a182c05ea4dea81bab73ecbbe9e013a79e99/src/compiler/types.ts#L693-L698)).
Expand Down

0 comments on commit 4ddda9b

Please sign in to comment.