Greetings all
I'm here again with another exciting topic, this article throws you into the world of Typescript and demystifies most fears you might have about it.
Inspiration
The inspiration behind this article was from a conversation with a friend who is a Backend Engineer and had just picked up React with a goal to merge both stacks(Frontend & Backend).
We were talking on a few topics and she mentioned being skeptical about taking on Typescript, as she was new to Javascript and the whole thing felt muddled up. At the time I could not talk much on it because prior to that conversation I had not written a single line of TypeScript, but I urged her to try it out as I could tell there wasn't much to it from the articles and videos I came across.
But after the conversation, TypeScript lingered on my mind, and I decided to dive into the documentation over the weekend and what I found out was pure GOLD!
So Let's Get To It 🐱🏍
What is Typescript
Typescript is an open-source object-oriented programming language created and maintained by Microsoft for applications with a massive infrastructure. TS serves as a static type checker which helps you be more explicit with your data structure, value types passed into and returned by functions, or used across your app. This way TS validates your JS ahead of time and lessens the amount of tests you will need to write.
Typescript is a superset of Javascript which means it has everything that Javascript has and more. Picture TS as a blueprint to your application, as it quickly helps you find your way if you happen to get lost in your code base and it also guides another developer around your application's code base if they were to work on it.
The browser can't understand TypeScript so it needs to be transpiled down to JavaScript. Basically an index.ts
file becomes index.js
.
Look at Visualizing TypeScript section for code examples.
A quote from Brad Green, an engineer at Angular
“We love TypeScript for many things… With TypeScript, several of our team members have said things like ‘I now actually understand most of our own code!’ because they can easily traverse it and understand relationships much better. And we’ve found several bugs via TypeScript’s checks.” — Brad Green, Engineering Director – Angular
Big Picture
Imagine you have an application with 50+ JS files, say after 6 months you need to quickly run into your code base and add a feature, make some changes or even fix a bug but then you spend hours probably trying to:
a) Understand how certain functions worked and what data types had to exist within, get passed into or returned by the function.
b) Figuring out the right approach to extending your application.
c) Figure out relationships amongst your data structure
TS abstracts all of that headache as you can simply go over your blueprint and be reminded on how your app was fit together.
Basic TS Data Types
- String
- Number
- Boolean
- Array
- Object
- Enum
- Tuple
- Any
- Undefined | Null
- Never
To learn more about these data types, check TypeScript's official documentation
Visualizing TypeScript
Here we have some TS code that lives in an index.ts
// a
let num1;
let num2: number;
num1 = 5;
num2 = 25;
// b
function congratulate(name: string) {
// say something awesome
}
// c
const square = (digit: number, power: number): number => {
return digit ** power
}
// OR
// d
function square(digit: number, power: number): number {
return digit ** power
}
a) Here we use let
so we can reassign a value to the variables. Looking at num2
you notice there is a colon :
directly infront of it and on the other side is number
. In plain English what this means is, you are declaring a variable named num2
which must be of type number
.
b) The same way the functioncongratulate()
takes in a parameter which must be of type string
c & d) With functions in TS you can go further as to describe which type of data is returned by adding a colon :
after the parenthesis housing the parameters, which is shown in the square
function.
When this .ts
file code gets transpiled into a .js
file the code looks like this
let num1;
let num2;
num1 = 5;
num2 = 25;
function congratulate(name) {
// say something awesome
}
const square = (digit, power) => {
return digit ** power
}
// OR
function square(digit, power) {
return digit ** power
}
We notice that the type declarations vanished and we have the regular JS syntax we are used to, note that upon runtime the type restrictions vanish, which makes the restrictions are valid only in development.
There are quite a few features in TS that enable you build the ideal blueprint for your app, and one of them is an Interface, among others like Types, Enums, and so forth...
Interface
These are used to strictly define the syntax or structure to be used for an entity. This can also be used to show relationships between data. Let us create interfaces for a Wizard character, a Spell and a Damage function
interface Wizard {
name: string,
age: number,
house: string,
favoriteSpells: Spell[],
spells: Spell[]
attack: (damage: Spell): void =>
}
interface Spell {
name: string,
damage: number,
isWizardStrongEnough: boolean
}
// arrow function
const damageWizard = (damage: Spell) => {
if (damage.isWizardStrongEnough) {
// do damage
} else {
// can't do damage because wizard not strong enough
}
}
Looking at the spells
field under the Wizard interface, we see another interface by the nameSpells
referenced with square brackets next to it and what this means is, that field only accepts an array of objects structured just like the spell interface, any object of a different structure would throw an error. This is one of the many ways to show relationships in your TS code.
Highly Recommended: If you don't have TypeScript installed locally but want to checkout how it works and transpiles to Javascript, use the playground
Types
In TS you can use Unions with Types to ascertain what structure to expect. Read more on Unions here
type Size = "small" | "medium" | "large";
OR
type FetchLoading {
loading: true,
errors: false
}
type FetchFailed {
loading: false,
errors: true
}
type FetchSuccess {
loading: false,
errors: false
data: {
name: String,
age: Number,
country: String
}
}
type Response = FetchLoading | FetchFailed | FetchSuccess;
Interface and Type are the most popular principles used in TypeScript, but there is a lot more like Enums, Classes, Unions, Generics, Namespaces which can be used, do make sure to check the TS handbook for more information on them.
Pros
You end up with a lot less bugs, some of which might occur from the wrong primitive value being passed in to functions or assigned to variables
The code is more expressive, the design intent of developers are visible through the TS inferences
TS supports class based object-oriented-programming, like inheritance and classes and a few more which help in building highly organized scalable code, as your app grows you will appreciate this synthetic sugar
Connections between every part of your application are validated and you get instant feedback during development if you go contrary to your blueprint
Cons
- Bloated code. To fully harness the power of TS you need to write more code which slows down development time.
Install Typescript
To use TypeScript on your local machine you need to have NodeJs installed. If you don't get it from NodeJS's official sitepick your platform and install. To be sure you don't have it installed, run node -v
in your terminal/command prompt, seeing a version number like v12.xx.xx
means you have it installed, if no response, go to NodeJs's official site
Now that we are sure we have NodeJs installed, we can now choose to install TypeScript on a project or global level.
Project level.
In your project root directory, where you have your package.json
file run npm install typescript ts-node
Or globally
npm install -g typescript
Check Install
Run tsc -v
to check if you already have TypeScript.
Resources
Conclusion
I do hope you enjoyed this brief overview on what TypeScript is and what it can be used for. If you're looking for a hands-on approach, you can checkout Maximilian Schwarzmüller's crash course on Youtube