-1

I wrote some code inside a .tsx file and I need to cast a variable but it doesn't work and I don't understand why.

That is my code :

let a : number = 2;
let b : string = a as unknown as string;
console.log("b type = "+typeof(b))

And that is the result :

b type = number

I think this is because I cast as unknown and then as string and I don't know why it's necessary but if I just write : let b : string = a as string;, I get the following error :

ERROR in App.tsx(59,22)
  TS2352: Conversion of type 'number' to type 'string' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first.

So does anyone know how to cast in .tsx file ? ( It's not possible to use <> for type casting otherwise it's considered as a React Element)

erwanlfrt
  • 111
  • 11
  • That *is* how to cast (actually [*assert*](https://www.typescriptlang.org/docs/handbook/basic-types.html#type-assertions)) in a .tsx file - *"when using TypeScript with JSX, only as-style assertions are allowed"*. `a as string` fails without the assertion via `unknown` because *`a` is obviously **not** a string*. – jonrsharpe Oct 20 '20 at 15:00
  • You are assigning a number but telling the compiler it will get a string, all Types etc are removed during compiletime, use `a.toString()` or `String(a)` – Zer0 Oct 20 '20 at 15:16

1 Answers1

2

If you're familiar with type casting in strongly typed languages, you may be misunderstanding what as string is doing. Remember that typescript only exists at compile time, not at runtime. So as string will not make any changes to the data at runtime, it will only affect how things are assessed at compile time. as string is a way to tell typescript "i know better than you do, so don't check the types here. Pretend it's a string, even though all the evidence says it's something else".

Using type assertions is occasionally necessary, but you should only use it if you actually do know something that typescript doesn't. The reason you're getting that error is that it's blatantly obvious that it's not actually a string, so typescript adds an extra layer to say "are you really sure you want me not to check your types?". Adding as unknown says "yes, really don't check my types".

If you want turn it from a number to a string, don't use type assertions; write code to change it to the other type:

let b : string = a.toString();
// or
let b : string = '' + a;
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • Thank you I get use to weakly typed language so I got some difficulties with type casting now. I thought it was able to translate a number 2 directly in String "2" without using toString(). – erwanlfrt Oct 20 '20 at 15:18