-1

What is the problem with the second situation?

function f(x) {   
    return (x as string).toLocaleUpperCase();
}

console.log("hello: "+ f("mr.")); // hello: MR.
console.log("hello: "+ f(0));

Uncaught TypeError: x.toLocaleUpperCase is not a function
at f (:2:14)
at :5:25
at HTMLButtonElement.excuteButton.onclick >(https://www.typescriptlang.org/play/playground.js:247)

kot
  • 7
  • 3
  • console.log("hello: "+ f("mr.")); // hello: MR. console.log("hello: "+ f(0)); // Uncaught TypeError: x.toLocaleUpperCase is not a //function – kot Jun 07 '19 at 13:05
  • 5
    0 is not a string, it doesn't have `toLocaleUpperCase` function. – Roberto Zvjerković Jun 07 '19 at 13:15
  • `(x + '' as string)` solves it, because you add a string to your variable, thus turning the number into a `string` (only `strings` have the toUpperCase functions) – elveti Jun 07 '19 at 13:32
  • I suspect you're missing tags - `x as string` seems like TypeScript. – Tyler Roper Jun 07 '19 at 13:35
  • Have a read of this: https://stackoverflow.com/questions/32554624/casting-a-number-to-a-string-in-typescript – frobinsonj Jun 07 '19 at 13:45

1 Answers1

0

from what I understand, your typescript code is transcribed into the following javascript code:

function f(x) {
    return x.toLocaleUpperCase();
}
console.log("hello: " + f("mr.")); // hello: MR.
console.log("hello: " + f(0));

And since numbers (like 0), don't have a toLocalUpperCase field, you get an error.

I'm not sure if this is the most typescript-ish way to do it, but here's an alternative that works for both your cases:

function f(x) {   
    return x.toString().toLocaleUpperCase();
}

console.log("hello: "+ f("mr.")); // hello: MR.
console.log("hello: "+ f(0));