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
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
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
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 analyzedAnnotation such as :
is telling the compiler that the assignment is fully valid
Casting as
is using an instantiated to force to take the shape as a type
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