190 points · by arbol · 2y ago · 203 comments
You really don't need the symbol - you can use an obscure name for the branding field. I think it helps the type self-document in errors and hover-overs if you use a descriptive name.
I use branding enough that I have a little helper for it:
/**
* Brands a type by intersecting it with a type with a brand property based on
* the provided brand string.
*/
export type Brand<T, Brand extends string> = T & {
readonly [B in Brand as `__${B}_brand`]: never;
};
Use it like: type ObjectId = Brand<string, 'ObjectId'>;
And the hover-over type is: type ObjectId = string & {
readonly __ObjectId_brand: never;
} const accountId: Brand<string, "Account"> = "123654"
Has the error Type 'string' is not assignable to type '{ readonly __Account_brand: never; }'You have to make a function to apply the brand via a cast, the article explains this as well.
function makeObjectId(id: string): ObjectId {
return id as ObjectId;
} const accountId = "125314" as AccountId
It makes sense that the technique uses casting.Another way you can implement the same: through a class constructor like new UserId('some string') which can also throw or let you handle operations on the class itself while allowing you to get the value.
I don't love that example though, because the brand field's value of a string literal will make it seem like the object actually has a property named `__brand` when it doesn't. `never` is the best brand field type as far as I can tell.
If you assert that your id's actually do have a never-typed field, and you let your program access it, you're basically letting users enter an impossible state freely and easily.
Is your problem the line wraps in the parent’s comment?
export type Brand<T, Brand extends string> = T & {
readonly [B in Brand as `__${B}_brand`]: never;
};
I count 14 different pieces of punctuation. you might as well use Perl at that point.I really like the pattern of value objects from Domain Driven Design. Create a class that stores the value, for example email address.
In the class constructor, take a string and validate it. Then anywhere that you need a valid email address, have it accept an instance of the Email class.
As far as I understand classes are the only real way to get nominal typing in TypeScript.
It is also possible to then infer a type from a class so you can use both the class where you want to discriminate types and the type where you really only care about the shape.
The absolutism towards OOP/FP -- instead of embracing the right use cases for each -- always ruffles me in the wrong way. C#, for example, does a great job of blending both OOP and FP (borrowing heavily from F# over the years). JS and by extension TS has the same flexibility to use the right paradigm for the right use cases, but it seems that everyone wants to be on one end of the spectrum or the other instead of accepting that JS is an amalgamation.
Evan You had a great quote on this where he correctly calls out much of the complexity and performance issues with React as being rooted in pushing against the language rather than embracing it.
[0] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
[1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Refe...
… also doesn’t need to proscribe use or non-use of classes. People were doing OOP in JS long before classes were added to the language. I routinely use classes in a FP style because they’re excellent for modeling value types with a stable structure.
type Email = Branded<string, 'email'>
function Email(maybeEmail: string): Email {
assertIsEmail(maybeEmail);
return maybeEmail;
}
function assertIsEmail(value: string): asserts value is Email {
if(!isEmail(value)) throw TypeError("Not an email");
return value;
}
function isEmail(value: string): value is Email {
return value.contains("@");
}
Versus: class Email {
#email: string;
public constructor(maybeEmail: string) {
if(!isEmail(maybeEmail)) throw TypeError("Not an email");
this.#email = maybeEmail;
}
valueOf() {
return this.#email;
}
}Although classes and instances are ultimately structural, right?
let foo = new Foo();
assert(foo.constructor == Foo);How are classes going to help? As far as I understand TS is structural period. Ex this is valid (!):
class Email {
constructor(public email: String) {}
}
let x: Email = new Email('foo@foo.com')
let y = { email: '73'}
x = y;For example, these two classes are distinct to TypeScript:
class Name {
constructor(private value: string) {}
getValue() {
return this.value;
}
}
class Email {
constructor(private value: string) {}
getValue() {
return this.value;
}
}
const email: Email = new Name(“Tim”); // Error: (paraphrasing) conflicting private declaration of “value”.I am surprised your code doesn't give an error, x and y are definitely not the same thing because `x instanceof Email` would be false at the end of that code. But like you said, to TS x and y are indeed the same type because they have the same structure. In practice both can be used interchangeably in the code (even if Email extended another class) with the sole exception of the `instanceof` keyword.
What's particularly better these days is that you get nominal typing and brand checks with standard private fields:
class Foo {
#brand;
static isFoo(o): o is Foo {
return #brand in o;
}
}Branding primitives is useful because you don’t otherwise have a name that you can control (e.g. feet versus meters as was suggested elsewhere in this thread, both of which would have type “number”).
The article starts with the example of two different object types with field “x: number”. In that situation you should be branding the field, not the object! If the field has the same name and the same branded type, structural typing is correct for that object shape.
- currencies
You may have some sort of integer representing the number of cents of some currency and you want to avoid doing operations between the wrong currencies (such as adding euros and pesos).
You can create branded types and functions that work on those Euro branded numbers and then decide how to do math on it. Or numbers representing metals and such.
It's useful in other scenarios such as a, idk, strings, you could theoretically brand strings as idk ASCII or UTF-8 or the content of an http body to avoid mixing those up when encoding but I want to emphasize that often many of those hacks are easier to be handled with stuff like dictionaries or tagged unions.
An example of what can be achieved with similar approaches (beware it's oriented for people that are at least amateur practitioners of functional programming) is Giulio Canti's (an Italian mathematician and previously author of t-comb, fp-ts, io-ts, optic-ts, and now effect and effect/schema), the money-ts library:
Branding is easily circumvented, so it's best as a developer hint that helps document APIs and alerts us to common mistakes as an incremental improvement over primitives.
For money and similar I would use objects and a custom math library.
And I'm struggling to think of where in a codebase I might want to hardcode Pesos or Euros.
My feeling is that while you can do this, you’re swimming upstream as the language is working against you. Reaching for such a solution should probably be avoided as much as possible.
For Rust I wrote newtype-uuid to provide newtype wrappers over UUIDs, which has already found a couple of bugs at Oxide.
Or you have a client library that you use to interact with your API, and the client library changes, and you don't even notice.
Or you change the return type of a function in a library, and you don't even know who all the callers are, but it sure would be nice if they all get a build error when they update to the latest version of your library.
Lots and lots and lots of ways for this to happen in a medium+ sized project that's been around for more than a few months. It's just another way to leverage the power of types to have the compiler help you write correct code. Most of the time most people don't mess it up, but it sure feels good to know that it's literally impossible to mess up.
It is equivalent to newtype in haskell.
Another example somebody mentioned here is a logged in user. A function can take a user and we need to always check that the user is logged. Or we could simply create a LoggedUser type and the compiler will complain if we forget.
A user is free to leave and rejoin a stream, and we want to retain old data. So each user_stream has columns id, user_id, stream_id (+ others)
Issues occur when people write code like the following:
streamsService.search({ withIds: userStreams.map((stream) => stream.id), });
The issue is easily noticed if you name the “stream” parameter “userStream” instead, but this particular footgun came up _all_ the time in code review; and it also occurred with other junction tables as well. Branded types on the various id fields completely solve this mistake at design time.
Right, but this is one of those situations where a reasonable person could conclude "The language is not working to help me solve the problem I'm trying to solve." Sometimes you don't want JavaScript sloppiness and you also don't want TypeScript structural-type "sloppiness," desiring instead nominal types.
This is a clever way to use the existing infrastructure to get nominal types with no additional runtime overhead.
The web is stuck with JavaScript, and Typescript is a tool to help us write maintainable JavaScript.
It’s the thing that made it an easy sell after everyone got turned off by the long-term experience of Coffeescript and such. It’s the reason various “better” typed languages that run on top of JS have flopped except with enthusiasts.
ListInterface list = new ConcreteList();
let runtimeType = GetTypeOf(list); // will be `ConcreteList`, not `ListInterface`
This is an imaginary java-like language, but I'm not aware of a statically typed language that gives you the static type resolutions at run-time, outside of cases like implicit generic resolutions and things like that.Funnily enough, Haskell[0] doesn't... unless you ask it to by explicitly asking for it via Typable[1].
[0] ... which is renowned/infamous for its extremely static+strong typing discipline. It is nice that one can opt in via Typeable, but it's very rare to actually need it.
[1] https://hackage.haskell.org/package/base-4.19.1.0/docs/Data-...
TS could have just as easily chosen nominal typing + a simple way to do typedefs and had everything else work like it does now. But structural typing gives you a lot of other useful features.
Try Dart, maybe you like it. It's like TS but with it's own runtime.
Determining types by what things appear to do instead of what they state they do seems like a generally unnecessary compromise in typing safety that isn't really worth the minuscule amount of effort it can save.
type UserId stringIt’s not about security, it’s about safety: make it harder to do the wrong thing, and make it easier to do the right thing than the wrong one.
Or perhaps I'm misunderstanding your comment. When you do `as OrgId` or `as UserId`, where do you envision those casts in ways that would require handling failures?
You can do this kind of thing in "proper" statically typed languages as well like "(Whatever)((Object)x)
The main problem in TS vs Java for this specific case is that if x is NOT Whatever then you get an error some point later in the code. In Java you would get the error immediately at the casting.
It makes debugging a bit trickier but I don't really run into these kind of problems all that often in my TS code and when I do they are usually easy to track down.
I don't think it has any relation to runtime type checking at all. It's refinement types, [4] or newtypes[5] depending on the details and how you shape it.
[1] https://github.com/microsoft/TypeScript/blob/main/src/compil... [2] https://github.com/microsoft/TypeScript/issues/4895 [3] https://github.com/microsoft/TypeScript/pull/33038 [4] https://en.wikipedia.org/wiki/Refinement_type [5] https://wiki.haskell.org/Newtype
This is both! The primary point of branded types is to allow you to use the type system to ensure that a particular runtime check has taken place.
I see. This is kind of cool, though the branding can still be broken via down-the-stream mutations. Would be nice to enforce re-branding every time a variable is changed, but that seems like a lot of overhead.
Only for mutable values! A branded string should be as immutable as they come, right?
Especially on the frontend, where your `throw new Error("Bad input type")` might brick the entire app if uncaught. I'd much rather hear an earful from TypeScript before a bundle is ever produced.
The article reads more like an endorsement of languages that do structurally-aware nominal typing (that is, languages that are nominally typed but that have awareness of structural equivalence so that zero-cost conversions and intelligible compile-time errors for invalid conversions are first class) than a persuasive case for the symbol-smuggling trick described.
C++'s templating lets express some very powerful type constraints... But good luck reading the compiler errors generated by someone else's very powerful type constraints that you haven't fully grokked to an implementation level.
Works especially well if you're using any kind of hexagonal architecture, make your functional core only accept validated/escaped/parsed/whatever types, and then the imperative shell must send any incoming data through whatever transformation/validation/etc before it can interact with the core.
However I just inlined the "tag". Also like yours but unlike OP there is no runtime tag. Which can be a pro (no extra code) or a con (can't do runtime checks).
I'm curious to see what the JS code looks like for casts and type checks in that case.
More like: magical disappearing type system is not nominal: hacky workarounds ensue.
I guess working in the pure logic and formalism of types is just addictive.
I love it.
Although if you do a bad job it might add a lot...
type ObjectId = string & {
readonly __tag: unique
symbol }
This way, we don't need to use `never`, but we still prevent the creation of a structurally equivalent type by mistake.I think Haskell avoid this by actually requiring you to write sound conversion functions between phantom types (it helps that phantom types don't involve any visible state at runtime).
Also nominal types for classes.
And correct variance.
And adhering to liskov substitution principles.
And exact object types.
And spread on types matching runtime behavior.
And proper no transpilation mode with full access to the language.
And has 10x less LoC than ts.
ps. before somebody says "flow is dead" have a look at flow contributions [0] vs typescript contributions [1]
[0] https://github.com/facebook/flow/graphs/contributors
[1] https://github.com/microsoft/TypeScript/graphs/contributors
Handling difficult cases leads to more type errors.
If type system is lax, it won't flag them but they can fail at runtime.
React has very little of $FlowFixMe annotations for its codebase.
In typescript projects on the other hand it's normal to see unsafety as normal code (casting, non null assertions, implicit and explicit anys etc).
Additionally, I've read a lot of typescript code, and the react codebase. My experience is different than yours. I see more type workarounds in react.
FWIW "$FlowFixMe" occurs 822 times in commit hash cf5ab8b8b2c92523aba0b982fb403add053a9110 out of 498900 lines of *.js source. That includes blanks and comments. I don't have any good stats on the occurrence of type assertions in typescript.
I expected thousands.
Fortunately it wasn’t and now I get to not-hate working in JavaScript.
They also fucked up typings in terms of community management.
Those two alone probably put them into downward spiral.
But the language is being developed with activity stronger than ever.
And it is well designed and pleasure to code in.
what does this even mean?
> And has 10x less LoC than ts
Prolly b/c Flow isn't able to express the advanced types (albeit with 10x LoC) in the first place.
What advanced types do you have in mind?
ps. the way you're using "albeit" sounds like you think flow has 10x larger codebase, it has 10x smaller codebase
Flow is more principled.
Sometimes I wonder what kind of programs are written using all these complicated TS types. Anecdotally, we use very simple, basic types in our codebase. The need for tricks like this (and other complicated types) is simply not there. Are we doing something wrong?
If you argue that this is not a common problem in practice, then I tend to agree. I haven't seen code with mixed up arguments very much, but when it does happen it can have bad consequences. IMO there is not a big cost to pay to have this extra safety. In TypeScript it's ugly, but in other languages that natively support this typing like Scala, Rust, Swift and Haskell, it works nicely.
Unless you accidentally create the wrong branded type? Which is as likely as disordered arguments.
As you stated, tests should cover this case trivially, I don't see the value in added type complexity.
I would also agree that it's harder to confuse complex types as any single instance of a type is unlikely to overlap once you have a few fields.
Data validation, typed database access, or functional programming libraries are good examples. Particularly the modern, leading libraries of such areas, if you look into their code you'll generally see very intricate typing. For FP libraries it's particularly tough. I like to use Remeda which emphasizes being very type-safe, but that means it's inherently more limited in what functions it can offer compare to other libraries which choose to compromise their type-safety. These kinds of techniques mean that libraries can offer greater functionality while remaining type-safe.
I could definitely see using something like this to force some constraints on my favorite bugbear for my problem domain: values that should have units. It matters a lot if "time" is nanoseconds, microseconds, or seconds, but most time-related functions just take in "number" like that's okay and won't cause thousand- or million-fold magnitude errors.
This is one way to provide some language safeguarding against treating 5 nanoseconds as the same as 5 microseconds.
It just depends on how constrained by types you want your code to be and how much time and effort you're willing to spend maintaining and writing code that fits within those constraints.
Sometimes complicated types are introduced because you want to maintain editor features such as find by reference and the ability to refactor later. When it works, removing or adding new features feels fast, easy and safe.
In the articles case you could differentiate between an email string type and a user id string type. Maybe sometime in the future you want to change the id to an integer instead, so now that it's already distinguished you could find all those places where that's applied.
That's at least a selling point, in practice I've used this a few times but it doesn't come up that often. Sometimes the blast radius of a type isn't big so it's not worth doing.