Key Topics Outline
- Statically Typed vs. Dynamically Typed Languages
- What is TypeScript and How Does it Work
- Benefits of Using TypeScript
- Is that all there is to TypeScript?
Statically Typed vs. Dynamically Typed Languages
Static typing is when you, the developer, explicitly declare the data type for each variable. Every variable’s data type must match their use case. For example, C++ requires you to specify the data type used before naming a variable and its assigned value. This is because the compiler needs to know the number of bytes to allocate in memory in order to effectively run the program. Because each variable needs to have its type defined on declaration, the size of the files for projects written in static typed languages can be larger than their dynamically typed counterparts.
Since static typing makes the usage of each variable more apparent, it can help reduce the amount of errors developers encounter. Now that you understand the basic difference between dynamic and static typing, let’s look at what TypeScript is.
What is TypeScript and How Does it Work
Benefits of Using TypeScript
Integrating TypeScript into your projects can save you time and additional effort. It includes the support for structuring your own types to define what properties to expect. As a result, intelligent code completion, or IntelliSense (for Visual Studio Code users), will be enhanced to auto-complete your created types’ properties, allowing you to work efficiently and practically in your development.
With an understanding of how TypeScript’s syntax looks and functions, let’s look at how TypeScript’s transpiler will inform us of our vulnerabilities before using the code. Consider the code snippet below, as we move through different ways TypeScript helps users ensure their variables are accurate:
In our first example, we see how the TypeScript transpiler notifies us when a data property is missing or is of the wrong type. Here we have removed the “email” property from the newly created user, “userOne”. Issues arise because all properties are defaulted as being required for the type. To mark a property as optional, use the question mark (?) when declaring it.
Now that we have updated the previous variable to its correct data type, the warning message is no longer an issue. TypeScript will also verify the correct data type when passing variables between functions. Consider our next example, where we call the returnUser function, but pass in a variable with the data type ‘string’ instead of ‘user’. TypeScript checks to see that returnUser expects a User instead of a string, and alerts us to the error.
Is That All There is to TypeScript?
Want more from GEO Jobe?
Check out the articles below or subscribe to our blog for more!