DEV Community

Discussion on: Understanding Generics in TypeScript

Collapse
 
plondon profile image
Philip London

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)
Enter fullscreen mode Exit fullscreen mode

We can now perform mathematical operations on this value with safety!

Collapse
 
iam_danieljohns profile image
Daniel Johns

I tried this and it still ran. Is this just a JS issue or am I missing something?

function returnStringOrNumber<T>(arg: T): T {
  return arg
}
let value = returnStringOrNumber<number>(123) + "hello"
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
plondon profile image
Philip London

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:

let value: number = returnStringOrNumber<number>(123) + "hello"
Enter fullscreen mode Exit fullscreen mode