Object.assign() vs Object Spread { … } In Angular Ngrx Reducers🥊

Tomas Trajan
Feb 27, 2018 · 6 min read
Image for post
Image for post
Sleep as good as this cat, Typescript has your back covered! (📸 by Sabri Tuzcu)

How to get better type checking and code completion support with Typescript in Angular Ngrx reducers or any other Redux-like library

Short recapitulation of Ngrx state library

Providing type information for the reducer

Typed actions

This makes it impossible to make a mistake when creating new actions

Typed actions are implemented using action type enum and corresponding action classes with type property and optional typed payload

Typed state

Example of a todos.reducer.ts file with all necessary type declarations for proper type-checking and code-completion support

Creating new state using Object.assign()

Creating new state object using Object.assign()
Objects with additional properties which are not specified in the type of the reducer state will unfortunately NOT produce type errors…
Specifying type variable for every Object.assign() parameter using Typescript generics will yield correct compiler errors but has problems on its own…

There must be a better way!

Object spread syntax for the rescue

Replacing Object.assing() with object spread syntax

Follow me on Twitter to get notified about the newest blog posts and interesting frontend stuff

Typescript correctly detects unsupported properties and reports them as type errors — Yaaay!

And voila, we simply cannot go wrong. Typescript got our back!

What about Redux?

Editor code completion support

Image for post
Image for post
Great Typescript powered code-completion support in Intellij IDEA editor

Code-completion is one of the best productivity related benefits of using Typescript

Hooray!

And never forget, future is bright

Image for post
Image for post
Obviously the bright future (📸 by Thomas Kelley)

Tomas Trajan

Written by

🅰️ Google Developer Expert for Angular #GDE ❤️ ️Typescript 🛠️ Maker of the @releasebutler and Medium Enhanced Stats 🌞 Obviously the bright Future

Tomas Trajan

Written by

🅰️ Google Developer Expert for Angular #GDE ❤️ ️Typescript 🛠️ Maker of the @releasebutler and Medium Enhanced Stats 🌞 Obviously the bright Future

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store