From 01df80f8ed062726bf3dfe42727113ee8e1e947a Mon Sep 17 00:00:00 2001 From: Stuart Schechter Date: Mon, 16 Sep 2019 09:55:41 +0900 Subject: [PATCH] Update nominalTyping.md Addresses: https://github.com/basarat/typescript-book/issues/521 Uses technique from: https://github.com/microsoft/TypeScript/issues/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. --- docs/tips/nominalTyping.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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)).