HomeToolsAbout a20k

Annotation and Assertion/Casting

What is Type Assertion/Casting

What is casting

Type casting is changing a type of a value from one type to another type

  • Casting is also known as Coercion

Type casting is you saying that you know the type conforms to the shape you are casting it as

  • There is no runtime checking or conversion of the type
    • The Typescript compiler trusts your coercion

Legit use cases for casting

When you are writing a Jest test for a component that uses a type with massive data shape and deep dependencies, you can work around it by creating a shallow data shape then cast on it instead

const mockedQueryResponse = { partialField: "partial", anotherField: "partial", } as IExpectedFullDataShape

Type casting vs Type assertion

Casting and Assertions are the same thing, but slightly different

The reason why it's not called type casting is that casting generally implies some sort of runtime support

  • However, type assertions are purely a compile time construct and a way for you to provide hints to the compiler on how you want your code to be analyzed

Rule: Annotation over Assertion/Casting

Differences

Annotation such as : is telling the compiler that the assignment is fully valid

  • If compiler disagrees, it will complain

Casting as is using an instantiated to force to take the shape as a type

  • you're telling the compiler what it should treat it as

Why avoid it

Type assertion (casting) does not change the underlying value

  • it only changes how the value is interpreted by the compiler or runtime environment

  • Improper type casting can lead to runtime errors or incorrect behavior if the actual value does not match the expected type

© VincentVanKoh