The most important typescript trick you'll ever learn

iway1

iway1

Posted on August 22, 2022

The most important typescript trick you'll ever learn

There's one thing typescript trick in particular that changed everything for me, and that's using the extends keyword in generic type parameters for the sole purpose of enabling inference:

function myFunctionInferred<Type extends Object>(v: Type) {
    return v;
}
function myFunctionNotInferred(v: Object) {
    return v;
}
Enter fullscreen mode Exit fullscreen mode

This allows typescript to infer the type of var, meaning that you will get superior type knowledge and intellisense for free:

// v is given the type {something: string}
const v = myFunctionInferred({something: 'value'}); 

// v is given the type Object
const v = myFunctionNotInferred({something: 'value'});
Enter fullscreen mode Exit fullscreen mode

Obviously we're getting a lot of additional information because of that type parameter! This is the simplest example possible and even it is potentially valuable.

What's even better is it opens up an entirely new world of free inferred type safety:

const someCoolObject = {
    keyOne: 'string value',
    keyTwo: false,
    keyThree: 5,
}

function myFunction<KeyType extends keyof typeof someCoolObject, ValueType extends typeof someCoolObject[KeyType]>(k: KeyType): ValueType {
    return someCoolObject[k] as ValueType;
}
Enter fullscreen mode Exit fullscreen mode

This gives us great autocomplete, of course:
Image description

But much more interestingly, v has its type inferred based on the string that gets passed to the function!

Image description

🤯 That's so cool! And it's extremely useful in practice, you just have to get creative.

💖 💪 🙅 🚩
iway1
iway1

Posted on August 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related