Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Nominal Typing for TypeScript 3.6.2 by forcing enums to be string enums #523

Merged
merged 1 commit into from
Sep 16, 2019
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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