Created
November 14, 2023 22:46
-
-
Save sigma-andex/dc69050ce1f4c053f3e29916022c0d45 to your computer and use it in GitHub Desktop.
newtype.ts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Newtype<S extends string, T extends any> = T & { readonly symbol: S} | |
type Currency = Newtype<'currency', number> | |
const wrap = <S extends string, T>(input: T): Newtype<S,T> => input as unknown as Newtype<S,T> | |
const unwrap = <S extends string, T>(input: Newtype<S,T>):T => input satisfies T | |
const over = <S extends string, T>(nt: Newtype<S,T>, f: (t:T) => T):Newtype<S,T> => { | |
const t: T = unwrap(nt) | |
const ft: T = f(t) | |
return wrap(ft)} | |
const eur: Currency = wrap(1) | |
const toDollar = (currency: Currency): Currency => { | |
return over(currency, c => c * 1.12) | |
} | |
const usd = toDollar(eur) | |
// const usd2 = toDollar(1.21) | |
console.log(usd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment