DEV Community

Madyan
Madyan

Posted on

TS Tip πŸ’β€β™‚οΈ Avoid the boilerplate with `typeof`

TLDR 😎

What issue are we solving here? πŸ€”

We all love TypeScript because it allows us to declare and enforce certain contracts for our types. E.g.

interface User {
  devCommunityUsername: string
  awesomenessLevel: number
}
Enter fullscreen mode Exit fullscreen mode

Now we can reuse this type everywhere the User object is expected:

function iAmExpectingAUserHere(user: User) {
  // now I can safely access user.awesomenessLevel 🀩
}
Enter fullscreen mode Exit fullscreen mode

However, there are instances where you have a huge object that you declare only once like:

const config = {
  username: 'Me',
  password: 'TheyAreWatching 😱',
  ... // imagine many more properties here
}
Enter fullscreen mode Exit fullscreen mode

Say you want to reference the type of this object. However, you don't want to declare a type explicitly as it'll lead into duplication, and with duplication comes maintenance cost (e.g. every time you add a property you need to declare it for the sake of using it in this single instance πŸ˜’)

Thinking...

Solution: type inference to the rescue πŸ¦Έβ€β™€οΈ

Turns out TypeScript has a special keyword to automatically infer the type of an existing object, which is exactly what we need here!

// use `typeof`
type Config = typeof config

// this is the same as:
type Config = {
  username: string
  password: string
  ...
}

// you can use it like 🀘
function doSomething(config: Config) { ... }
Enter fullscreen mode Exit fullscreen mode

Looking for more TS tips? πŸ‘‡

I've recently started tweeting daily tips like the one above. If you've enjoyed it and want to continue learning, follow me for more TypeScript tips ✨

Follow me for TypeScript tips

Top comments (3)

Collapse
 
stereoplegic profile image
Mike Bybee • Edited

TypeScript devs keep telling me that "nothing in TypeScript interferes with a junior dev's ability to learn JavaScript..."

Exhibit A:

"TypeScript uses the typeof keyword for capturing anonymous types. Despite the same name, it is very different from JavaScript's typeof operator β€” in fact, the two can only appear in mutually exclusive places."
-- Marius Schultz

Collapse
 
madyanalj profile image
Madyan

Agreed. I definitely think there is a steep learning curve for TS, especially when it comes to advanced typing concepts such as the one mentioned in this post and generics. I strongly believe it's worth it in the long term though, especially when you're authoring a library for others to use (whether the library users use TS or plain JS)

Collapse
 
stereoplegic profile image
Mike Bybee

I don't agree (especially when it comes to mixing annotations in with the function declarations themselves, and having seen the long term effects on both project organization firsthand, and on junior dev learning), but I understand the rationale.