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;
}
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'});
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;
}
This gives us great autocomplete, of course:
But much more interestingly, v
has its type inferred based on the string that gets passed to the function!
🤯 That's so cool! And it's extremely useful in practice, you just have to get creative.
Top comments (0)