Branded types for TypeScript
carlos-menezes.com
Branded types for TypeScript
1–10 of 152 posts
Re: Branded types for TypeScript
#2Re: Branded types for TypeScript
#3The complication with TypeScript is that it doesn’t have nominal typing. Instead, it has ‘structural typing’: type equality is based on what the type contains. So you could define a new type ‘Hash’ as a string, but ‘Hash’ would just be a synonym — it’s still considered interchangeable with strings. This technique of ‘branded types’ is simply a way to simulate nominal typing in a structural context.
Re: Branded types for TypeScript
#4Really ugly way to avoid something already solved by named parameters and/or namespacing
Re: Branded types for TypeScript
#5Really ugly way to avoid something already solved by named parameters and/or namespacing
Re: Branded types for TypeScript
#6In most languages, doing what this article describes is quite straightforward: you would just define a new type (/ struct / class) called ‘Hash’, which functions can take or return. The language automatically treats this as a completely new type. This is called ‘nominal typing’: type equality is based on the name of the type. The complication with TypeScript is that it doesn’t have nominal typing. Instead, it has ‘st…
Well, no. In most languages you wind up making a typed wrapper object/class that holds the primitive. This works fine, you can just do that in TypeScript too.
The point of branded types is that you're not introducing a wrapper class and there is no trace of this brand at runtime.
Re: Branded types for TypeScript
#7Re: Branded types for TypeScript
#8It's called "nominal typing", because the types have names. I don't know why it's called "branded" instead here. There's probably a reason for the [syntax choice].
Old idea but a good one.
Re: Branded types for TypeScript
#9In most languages, doing what this article describes is quite straightforward: you would just define a new type (/ struct / class) called ‘Hash’, which functions can take or return. The language automatically treats this as a completely new type. This is called ‘nominal typing’: type equality is based on the name of the type. The complication with TypeScript is that it doesn’t have nominal typing. Instead, it has ‘st…
> In most languages, doing what this article describes is quite straightforward Well, no. In most languages you wind up making a typed wrapper object/class that holds the primitive. This works fine, you can just do that in TypeScript too. The point of branded types is that you're not introducing a wrapper class and there is no trace of this brand at runtime.
Re: Branded types for TypeScript
#10https://www.kravchyk.com/adding-type-safety-to-object-ids-ty...