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
}
Now we can reuse this type everywhere the User
object is expected:
function iAmExpectingAUserHere(user: User) {
// now I can safely access user.awesomenessLevel π€©
}
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
}
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 π)
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) { ... }
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 β¨
Top comments (3)
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
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)
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.