diff --git a/docs/tips/nominalTyping.md b/docs/tips/nominalTyping.md index c37546c1d..64bfa3d2b 100644 --- a/docs/tips/nominalTyping.md +++ b/docs/tips/nominalTyping.md @@ -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; /** @@ -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)).