Beginners Guide to TypeScript: Part 2
In the previous article we went over in high level what and how TypeScript works and the differences of JavaScript types verse TypeScript types. If you need a refresher you can check out the blog post here.
Now we can move on to how we define types in our code from the e-book Tackling TypeScript. We do this by type annotations!
Type Annotations
TypeScript lets you define types for variables, function parameters, objects, and more by using type annotations.
Below example using parseInt() shows the two type annotations in TypeScript.
function toNumber(str: string): number {
return parseInt(str);
}
The parameter str
is followed by : string
. This tells us all arguments must be a string
.
The closing parameter’s parentheses is followed by : number
. This tells us the return value must be a number
.
Note once an identifier(name given to elements like variables/functions) is annotated with a type, it can only be used as that type. If the identifier uses a different type, the TypeScript compiler will throw an error.
Type Inference
TypeScript can infer(conclude) a static type
if there is no type declared.
A Reminder, static type
is when the TypeScript compiler enforces that the identifier uses the correct type.
For the above example, if we remove the return type of toNumber
, TypeScript will be able to infer that the return value is a number
. This is not magic 🪄, TypeScript follows a strict set of rules for figuring unstated types.
function toNumber(str: string) {
return parseInt(str);
}
Two Languages Levels: Dynamic and Static
Above we mentioned static type
but TypeScript actually has two language levels!
- dynamic level - is done by JavaScript and is made up of code and values at runtime
- static level - is done by TypeScript and is made up of static types during compile time
Something to remember is that values
exist at the dynamic level and types
exist at the static level. We can see these two levels in the below example.
const nullVal: null = null;
At the dynamic level we use Javascript to declare a variable nullVal
and initialize it with the value null.
At the static level we use TypeScript to specify that the variable nullVal
has a static type of null
.
null
appears twice but means two very different things depending if it is used at the dynamic level or static level.
Tackling TypeScript states that it is important to keep in mind these two language levels. This will help us understand TypeScript better 🎉
That is it for this blog! Here we learned type annotation, that TypeScript can sometimes infer types, and to keep in mind the dynamic and static language levels when writing TypeScript. In my next article I will cover type aliases and much more!