Skip to content

Commit

Permalink
Update nominalTyping.md
Browse files Browse the repository at this point in the history
Addresses: basarat#521
Uses technique from: microsoft/TypeScript#32891

Also note: This "& string" that remains in this code sample appears to do nothing as of TypeScript 3.6.2, but presumably should be kept for backwards compat.
  • Loading branch information
UppaJung committed Sep 16, 2019
1 parent 355290d commit 01df80f
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 01df80f

Please sign in to comment.