Reduce Duplication
Loading "Reduce Duplication"
Run locally for transcripts
π¦ These last two steps have little to do with React and everything to
do with TypeScript. If you'd rather skip these two, I won't be offended π₯²
π¨βπΌ One last thing that bugs me is the repetition in the
operations
type. The
type for every one of those functions is the same. They all accept two numbers
and return a number.One thing we could do is extract that function into a type and then tell
TypeScript that the
operations
object is a Record
where the key is one of
the valid operators and the value is an OperationFn
.I'm going to let you try this one on your own.
π° But I'll give you some hints:
- You'll need π
TypeScript's
Record
Utility Type - You'll have to manually create a union of all allowed
operations
again for the Record'skey
- You'll need to define π a function type for the Record's value
π¦ At the end of this one, you may prefer the previous version and that's fine.
This is just two ways to do it and they both come with trade-offs. Personally, I
prefer this way to avoid typing all the functions individually.
π¦ Also, you may wonder why we went back to repeating ourselves. Unfortunately
there's no way around it if you want to define the object as a Record with a
specific key. However! It's not as bad as before because if we make a mistake
and forget to update both places, the compiler will complain at us rather than
having a runtime error, so it's less of a problem. And there's actually a
workaround for this, which is what the next step is all about!