Given the code below, are there cleaner ways to express many nested map functions in TypeScript? I love the Scala "for-comprehension" for this use-case, but I can't find the equivalent in TypeScript. I feel like I'm missing something pretty obvious here.
I have several objects that can fail instantiation for validation reasons, so the return types are all Either<string, T>
. For instance:
const userId: Either<string, UserId> = UserId.create('1234')
When composing objects that are made up of many statements like the one above, it gets gnarly to look at. All variables in the example have been replaced with strings for readability.
In TypeScript, this is what I'm doing. Is there a cleaner way to express this without losing my types?
const userSettings: Either<string, UserSettings> = UserId.create('1234').chain(userId => {
return Email.create('hello@world.com').chain(email => {
return Active.create(183).chain(active => {
return Role.create('admin').map(role => {
return UserSettings(userId, email, active, role)
})
})
})
})
In Scala, I would express the above code like this:
for {
userId <- UserId.create('1234')
email <- Email.create('hello@world.com')
active <- Active.create(183)
role <- Role.create('admin')
} yield UserSettings(userId, email, active, role)
I'm using the Purify library for types such as Either.
Does anyone have any tips, suggestions, and/or libraries that could help clean up my nested map functions TypeScript mess?