Skip to content

Instantly share code, notes, and snippets.

@zeddee
Last active January 25, 2022 05:07
Show Gist options
  • Save zeddee/ba7ba4d960e78e11c5fb371196ed6a03 to your computer and use it in GitHub Desktop.
Save zeddee/ba7ba4d960e78e11c5fb371196ed6a03 to your computer and use it in GitHub Desktop.

Typescript notes

a as b is not type casting

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:

  1. 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 an as operation on a value of one type into another type. By design, the as operator is meant to narrow down the possible types that a given value can be.
  2. When we check the type of a1 and b1 (after type assertion), we find that they still take their types from the value we've performed the as 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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment