Typescript for beginners.

Typescript for beginners.

I just learned TypeScript last night, even though it’s just the basics. I learned about what TypeScript is, the differences between TypeScript and JavaScript, and how TypeScript works. After learning, I prefer to write about it because, for me, that’s the best way to learn something new. Okay, let’s continue!

What is TypeScript?

TypeScript is basically JavaScript. TypeScript has all the features of JavaScript, but JavaScript does not have the features of TypeScript. JavaScript uses Dynamic Typing, which means that every variable you write in JavaScript defines its data type automatically. However, in TypeScript, you have to explicitly define the data type if you want to create a variable. This is called Static Typing. For example:


//create variable in Javascript 

let a = 1 
let b = 2 

console.log(a+b) 

//print 3
        

That is an example of Dynamic Typing where you don’t have to declare the data type; you can simply write the variable, and the type is inferred automatically. Dynamic Typing is easier than Static Typing, but writing code like this can lead to some issues. For example:


//issue dynamic typing in Javascript 

let a = 2 
let b = true 

console.log(a+b) 

//print 3
        

Do you see the code above? When a number meets a boolean in JavaScript, JavaScript will treat the boolean as a number. So, when you sum and console log it, it will print 3. You can observe this behavior. However, in TypeScript, this issue will never occur because you explicitly declare the data type. For example:


//Create Variable in Typescript 

let a: number = 2 
let b: number = 3 

console.log(a+b); 
//print 5 

let firstName: string = "syahrul" 
let lastName: string = 10 

console.log(firstName + lastName) 
//print ERROR!!
        

That is an example of Static Typing, where you have to declare the data types for variables. By writing the code like that, it minimizes the occurrence of errors.

How Typescript Works?

Okay, before we continue with how TypeScript works, let me explain how JavaScript works first. In JavaScript, we typically use console.log to print something to the console without a compiler, allowing you to detect errors at runtime. Unlike JavaScript, TypeScript has a compiler called TSC (TypeScript Compiler) which enables you to detect errors early, before runtime. This is how TypeScript works: you write the code in TypeScript and then compile it. If there are no errors, it will create a JavaScript file. if there are errors it wont create Javascript file.

Typescript → TSC → Javascript

That’s it! In simple conclusion, TypeScript is like JavaScript but with additional features that make JavaScript even better. After writing this, I will continue learning TypeScript, especially focusing on Data Types in TypeScript. I will update it again on Medium. Thanks for reading!