Have you ever wanted to use javascript, but with obligatory types to ensure the code is easy to maintain? Well, someone at Microsoft did a long time and now, we shall take a look at typescript: a “super set” of javascript, adding better maintenability, static typing, checks, etc to help make your code better before deploying.
Let’s dive in!
What is Typescript?
TypeScript is a programming language that builds upon JavaScript, one of the most widely used languages for web development. What makes it special is the ability to add a layer of safety and structure to JavaScript code. Its goal is to help catch errors and bugs in your code during development rather than at runtime, making your code more reliable.
The language was created by Microsoft and first announced by Anders Hejlsberg, a prominent software engineer at Microsoft, on October 1, 2012. TypeScript was developed to address the challenges and limitations of writing and maintaining large-scale JavaScript applications, by adding static typing, interfaces, and other features to help developers write safer and more maintainable code.
While technically compiled, as typescripts gets compiled to javascript before running, typescript is a JIT language, just like with PHP. This means that the code is initially run by an interpreter that will then dynamically compile and optimize code on the spot whenever it needs extra performance.
1. Installation
To use TypeScript, you need to install it globally on your computer. You can do this using Node Package Manager (NPM).
First, get NPM by downloading node.js and installing it. For Windows and MacOS, go to https://nodejs.org/en/download. For Linux, just run sudo apt install nodejs
or go to the same link and download from there. With node.js and npm installed, run the following command to get typescript(any system)>
npm install -g typescript
2. Basic Types
TypeScript has several basic types:
number
: for all numbers, both integers and floats.string
: for text.boolean
: for true or false values.null
andundefined
: for empty or unassigned values.any
: for variables that can have any type.
let age: number = 25;
let name: string = "Alice";
let isStudent: boolean = true;
let maybeNull: null = null;
let unknown: any = "Hello";
And as the name implies, types are mandatory on typescript.
3. Variables and Constants
You can declare variables using let
and constants using const
. Just like with any programming language, variables can change their values, but constants cannot.
let counter: number = 0;
const pi: number = 3.14;
4. Functions
Functions are blocks of code that perform a specific task and which can be repeated throughout your code. You can specify input and output types using type annotations.
function add(a: number, b: number): number { //function must receive numbers for input and outputs a number
return a + b;
}
console.log(add(1,2))//will output 3
5. Interfaces
Interfaces define the structure of objects, making sure they have specific properties and methods.
interface Person {
name: string;
age: number;
}
const person: Person = { name: "Bob", age: 30 };
console.log(person.name)//Bob
console.log(person.age)//30
They will work kinda like other types, as in they can be used as argument type for functions:
interface mynumbers{
number1: number;
number2: number;
}
function addnumbers(nums: mynumbers){
console.log(nums.number1+nums.number2)
}
addnumbers({number1:1,number2:2})//output: 3
6. Classes
Classes let you create objects with methods and properties. They can also implement interfaces.
class Animal {
constructor(public name: string) {}
makeSound() {
console.log(`${this.name} makes a sound`);
}
}
const cat = new Animal("Whiskers");
cat.makeSound(); // Outputs: "Whiskers makes a sound"
7. Arrays and Tuples
Arrays hold collections of data of the same type. Tuples are arrays with a fixed number of elements, each with a specific type. This is very similar to how Rust does things.
let fruits: string[] = ["apple", "banana", "cherry"];
let coordinates: [number, number] = [2, 3];
8. Type Assertions
Sometimes TypeScript can’t infer the type correctly. You can tell TypeScript the type using type assertions.
let userInput: any = "123";
let parsedInput: number = parseInt(userInput as string);
The example above assures that the user input will be stored as string.
9. Enums
Enums allow you to define a set of named constants, making your code more readable and easily documenting intent. TypeScript has numeric and string-based enums.
//Numeric Enum
enum UserResponse {
No = 0,
Yes = 1,
}
console.log(UserResponse.Yes)//1
//String Enum
enum Direction {
Up = "UP",
Down = "DOWN",
Left = "LEFT",
Right = "RIGHT",
}
console.log(Direction.Right)//"RIGHT"
10. Modules
You can split your code into separate files and import/export functionality between them. This further helps with organizing code.
math.ts
export function add(a: number, b: number): number {
return a + b;
}
main.ts
import { add } from "./math"; //imports just the add function from math.ts
let result = add(2, 3);
That’s it for the basics of TypeScript! And as always, if you want to go beyond the basics, you’ll need practice. So happy coding!