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:
function returnStringOrNumber<T>(arg: T): T {
return arg
}
const myStringOrNum = returnStringOrNumber<number>(123)
We can now perform mathematical operations on this value with safety!
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:
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: