“Typecast types in Typescript” : that’s three “types” in a sentence with three significant words, and for that, I should tap out (but I don’t).
We see a lot about “type assertions” in to type conversations (or conversions!) in Typescript. Type assertions enable you to override default type inference for neutral types. We have discussed about type assertion before.
Typecasting refers to type conversions. While they don’t function similar to other strongly typed languages, they do exist.
We will see more of type assertions and casting after this preface.
Types, you say?
For a basic introduction of “types” - head over to types in Typescript and Javascript types.
Typescript supports -
- built-in types (basic e.g.
number
,string
,boolean
,and special types e.g.any
,unknown
) - additional types (e.g. collections like
enum
and even user-defined types)
You define variables with types -
|
|
It’s all a good world with types until it isn’t. It so happens that -
- you (think you) know more than what the compiler knows. You want to tell compiler that a variable is of a specific type.
- values may need to be moved across types in the course of doing something
Type Assertions and Typecasting
The process of changing types is what is called “type casting”. Typecasting in strongly typed languages like C# allow us to convert types.
|
|
The code checks whether a given string is a valid number and outputs the number. The “string” or “number” types are treated in a consistent way by both the compiler and runtime engine.
Typescript behaves differently. It is compiled to Javascript, which does not give two hoots about your defined types, and there is no “runtime” to enforce types during execution. All Typescript can do is to apply all its smarts during compilation of Typescript to Javascript code.
Type assertions let the Typescript compiler know that a given variable should be treated as belonging to a certain type. There are no “exceptions” or data restructuring associated with assertions, except minimal validations (we refer this behaviour as “validations that are applied statically”).
But, implicit types do exist during program execution, and type conversion behaves similar to Javascript since the execution engine is, well, Javascript. But, you need to make explicit conversions in Typescript to humour the compiler, and probably, everyone else in your team.
Aside: IMO it is more fun to use implicit conversions that reduce code, confuse people and make it hard to write tests.
When & where to use type casting and type assertion?
Type assertions helps you to force types when you are not in control of them. For e.g. -
- you are processing user data (with unreliable types)
- working with data that has changed shape over years (employee code was numeric, now it is alphanumeric :))
- receiving data from an external program
Consider this example that uses any
, a special type that represents any type in Typescript. You convert any
to a specific type to process it further -
|
|
We can start with any
and use type assertion to denote that the variable is in fact a number.
|
|
Or, consider this example with unknown
, another special type in Typescript -
|
|
The compiler does not know better about any
or unknown
variables to process further - so we make the compiler “see” the variables for what they really are.
Typecasting, on the other hand, helps you to convert types and provide consistent (expected) results :). For e.g. -
- concatenation of a number and string
- convert arrays of numbers to strings for formatting and display
How do I assert types?
There are two ways to do type assertions.
- Bracket syntax. e.g.
let length: number = (<string>lengthField);
- Use
as
. e.g.let length: number = (lengthField as string);
There is no difference between the two ways and the end result is always the same. Note that if you are using JSX you have to use as
syntax.
Type conversion in Typescript
Converting specific types is similar to Javascript.
From _ to String
We convert any type to string by using String(x)
or x.toString
.
|
|
From _ to Number
This is so radically different from string.
|
|
There are additional helper functions that, well, help you do strange things -
|
|
From _ to Boolean
Convert “stuff” to boolean.
|
|
From object
to array
Yes, you read that right - let’s see an example of converting object to array in style. Not quite a glaring example of “type conversions”, but apparently, people stare in awe at such code.
|
|
The End
We saw type assertions, typecasting and examples of type conversions. Hopefully that has confused you a bit more about the wonderful world of types.