How to cast inside .tsx file?

611 views Asked by At

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)

1

There are 1 answers

1
Nicholas Tower On BEST ANSWER

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;