Quick note! If you'd like to experience this post interactively, go to https://codeamigo.dev/lessons/151
Introduction
Sometimes when ...
For further actions, you may consider blocking this person and/or reporting abuse
This is a great explanation but I'm still unsure of a situation where I would use generics.
The above example can have multiple return types without the need of a generic.
So I'm not sure how a generic would add to that. Granted, that's mostly due to my lack of understanding of generics in the first place 😄
Hey Mike! Did you checkout the interactive tutorial? Maybe that would be helpful as well!
To answer your question, let's say we used
returnStringOrNumber
and assigned a variable to it.const myStringOrNum = returnStringOrNumber(123)
Now try performing a mathematical function on myStringOrNum! TypeScript doesn't know if that's valid or not because as we said, returnStringOrNumber might return a string!
However, if we used generics:
We can now perform mathematical operations on this value with safety!
I tried this and it still ran. Is this just a JS issue or am I missing something?
Hey @iam_danieljohns that's perfectly valid JavaScript, in this case value will be cast to a string type because concatenating a number and a string results in a string. In this case value will be "123hello".
If you wanted to make sure that value was indeed a number type you could do:
Think consuming an API, you can get different types of responses, here generics are gold , because you create the function to consume once using generics and you just specify the type when you use it
That's a very good point :)
Most of the time you need to use generics when one argument depends on another catchts.com/infer-arguments or you need to do some validation catchts.com/type-negation , catchts.com/validators
Thanks for the resources!
Simple and objetive description abou how generic works in typescript.
Very good! I will recommend it.
I'm learning TypeScript right now, and this was a really simple, digestible way of explaining the topic, thank you!
Good reading! I think that instead of a ThingWithLength you could simply replace that with an Array just in case someone would expect more array methods from it :)