newtypeis a construct that allows you to create a nominal type from another type. (Recall that Haskell and Typescript are both structurally typed.) One use case is to allow differentiation of two values with the same underlying type, where one value needs to follow a separate set of constraints.
strings; however, we have several functions that want to ensure they only receive either fiat symbols or crypto symbols. How can we enlist the type system's help here, while keeping our values as regular strings?
[Unique]object key is a trick for hiding the tag from an editor's autocomplete (credits to Dan Freeman's great article for this trick).
type CryptoCurrencywhich is really just a
string, but will be handled nominally rather than structurally, such that if we try to pass a
stringto a function that expects a
CryptoCurrency, we will get a type error. Contrast this with
export type CryptoCurrency = string, which would be like the Haskell type synonym
type CryptoCurrency = Stringinstead of
newtype CryptoCurrency = String.
newtypelives entirely in the type system.
serializeDate = (date: DateRecord): stringand a deserializer
parseDate = (str: string): DateRecord, both of which do some validation. We can improve type safety and reduce the chances of deserialization errors by changing
stringin these signatures to a
newtype. Now, we can be sure that we are only ever passing the "right" strings to
parseDate. We can also go a bit further by typing all other sources (like API responses) with