Type Casting with TypeScript
Type casting is the practice of defining the function or code as best as you can. Below are some basic types that TypeScript checks for:
- string: “TypeScript is awesome!”
- number: 0, 1, 2, etc.
- object: { language: “typescript” }
- boolean:
true
orfalse
- undefined: Data is not defined
- void: Nothing
- any: Literary any data type
Let’s annotate our alertMe()
function using these types. To annotate an argument or function, you use the colon (:
) followed by the type.
function
alertMe
(
message
:
string
)
:
void
{
alert
(
message
);
}
In this case, we are explicitly defining the message
parameter as a string and nothing else. If you compile this function again using the tsc
command, this time with the one instance of alertMe()
. But this time, pass in a number instead. You will still receive the same error! At this point, TypeScript is no longer inferring the type; this type it’s explicitly stated.
You should have noticed something...