Before I jump into describing and elaborating on our title, I'd like to first introduce TypeScript a little bit.
What is TypeScript?
When you develop on large scale with JavaScript you realise that it has it's pros and cons. The cons get highlighted hugely especially when working with multiple files mostly at runtime. Don't get me wrong , I โค๏ธ JavaScript but we can all agree it has it's shortcomings.
TypeScript is basically a superset of JavaScript only that is has a type system which makes it stricter . "Because TypeScript is a superset of JavaScript, you could also think of JavaScript as a subset of TypeScript. And that means that our entire TypeScript toolchain is perfectly happy to process JavaScript and provide all the services on top of JavaScript," says TypeScript co-creator, Anders Hejlsberg.
Simply put, TypeScript is able to identify developmental bugs way before they cause major at runtime.
Type Inference
Static typing is when the compiler enforces that values use the same type which means that the data type of a variable has to be the same as the value initially assigned when declaring the same variable in TypeScript
In JavaScript, you are able to assign any value to any variable. Below is a valid piece of code in JS:
let banana = 9 ;
banana= "Nine";
Here is the same piece of code in TS:
let banana = 9 ;
banana= "Nine"; //let banana: number, Type 'string' is not assignable to type 'number'.ts
Some advantages of using TS
TypeScript goes further to introduce Enums and OOP concepts.
Enum
TS
enum Veggies {
Kale,
Cabbage,
Coriander,
}
let v: Veggies = Veggies.Kale;
JS
var Veggies = {
Kale: 0,
Cabbage: 2,
Coriander: 3,
}
var v = Veggies.Kale;
v = 7000;
Object Types
Javascript allows us to pass data through objects while in TS we use object types which can be in 3 ways namely:
function greet(person: { name: string; age: number }) {
return "Hello " + person.name;
}
interface Person {
name: string;
age: number;
}
function greet(person: Person) {
return "Hello " + person.name;
}
type Person = {
name: string;
age: number;
};
function greet(person: Person) {
return "Hello " + person.name;
}
There's so much you to learn about TypeScript. I highly recommend visiting TypeScript Handbook to learn more. I'll try to be writing more on the subject and how you can use it with other server side languages to build pretty cool stuff end to end. Hope they help ๐