DEV Community

Discussion on: Understanding Generics in TypeScript

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