The a as b
operation may look like a type casting or type conversion operation, but it is not.
a as b
actually performs a
type assertion.
No type conversion or "casting" happens.
We see this when we try to run:
const a:string = "Hello"
const b:number = 5
const a1 = a as unknown as number
const b1 = b as unknown as string
console.log(`Type of a: ${typeof(a)}`)
console.log(`Type of a1: ${typeof(a1)}`)
console.log(`Type of b: ${typeof(b)}`)
console.log(`Type of b1: ${typeof(b1)}`)
// Type of a: string
// Type of a1: string
// Type of b: number
// Type of b1: number
The above code compiles. But you can see here that:
- We're lying to the typescript compiler -- by asserting an
unknown
type before re-asserting the target type. Typescript doesn't allow you to directly perform anas
operation on a value of one type into another type. By design, theas
operator is meant to narrow down the possible types that a given value can be. - When we check the type of
a1
andb1
(after type assertion), we find that they still take their types from the value we've performed theas
operation on. No type casting/conversion has occurred.
Instead, we should manipulate types using vanilla Javascript:
const a: number = parseInt("Hello")
const a1: number = Number("Hello")
const b: string = (5).toString
const b1: string = String(5)