JavaScript on Steroids: Why and How Pros use TypeScript
With the surge in popularity of TypeScript, we are witnessing a humongous number of developers ditching JavaScript in favor of TypeScript. Often junior developers are left scratching their heads over why the shift is taking place and how to make the most of it.
This article will help you nail TypeScript and provide insights into why it is better than JavaScript.
Why TypeScript?
Before we start with Why, we should probably look at What is TypeScript?
TypeScript is a programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript and adds optional static typing to the language. TypeScript is designed for the development of large applications and transcompiles to JavaScript
TypeScript adds an additional layer of static typing
, which helps the developer avoid a lot of difficult-to-find bugs at development time instead of runtime. It also helps a lot in IntelliSense, providing precise code completion suggestions, so no more stumbling around in the dark.
TypeScript is nothing but JavaScript with some additional features and can be compiled as per ES5 and ES6 standards to support the latest browser. When combined with IDEs like VS Code, it can save developers hundreds of hours.
Getting Started
Installing TypeScript
Before writing any TypeScript code, we need to install the TypeScript package first.
npm install -g typescript
Keeping TypeScript installed as a global package is a good idea as it will allow node to execute TypeScript files directly using node <file.ts>
. But for a project, you should install it as a local package using
npm install -D typescript
Initializing a TypeScript Project
To initialize a TypeScript project, we need to create a tsconfig.json
file in the root directory of the project. You can auto-generate it using
tsc --init
Compiling TypeScript
To compile TypeScript files & watch for changes, navigate to the file directory and use
tsc -w
TypeScript Features
With TypeScript setup, let’s take a look at the features TypeScript has to offer.
Types
Since TypeScript is a strongly typed language, it makes sense to start off with its type system. The variable types can be defined as follows
const userName: string = "John Doe";let age: number;
age = 30;const arr: number[] = [1, 2, 3]; // array
const tuple: [string, number] = ["John", 30]; // tuple (fixed size)const nullValue = null; // infered type
NOTE: If you access index > 1
in the tuple above or assign a non-number value to age
, TypeScript compiler will throw an error, making sure you fix the code before execution.
You can also create custom types to suit your specific needs.
type User = {
name: string;
age?: number; // Optional property (`age` can be undefined)
(): number; // type is callable (returns number)
new (name: string): User; // can be called as a constructor
readonly id: string; // cannot be modified after creation
signIn: (retryCount: number) => void; // function
customConstant: "constant"; // value can only be "constant"
get fullName(): string;
set username(name: string);
};type UserAges = {
[id: string]: number; // index signature mapping string to number
};type Pi = 3.14; // value type
const pi: Pi = 3.14;
TypeScript also allows you to create union
, intersection
, and enum
types.
// union type
type Size = "small" | "medium" | "large";// intersection type ({ x: number; y: number })
type Coordinates = { x: number } & { y: number };// enum type (the values will be assigned from 0 to N)
enum SizeEnum {
Small,
Medium,
Large,
}// enum type (with string values)
enum SizeStringEnum {
Small = "small",
Medium = "medium",
Large = "large",
}const size: SizeEnum = SizeEnum.Small;
Generics
In case you don’t know the type of the variable, you can use Generics
to allow the compiler to infer the type.
function clone<T>(o: T) {
return JSON.parse(JSON.stringify(o)) as T;
}
Interfaces
TypeScript also allows you to create interfaces
. An interface
defines the shape of an object.
interface User {
name: string;
age?: number;
(): number;
new (name: string): User;
readonly id: string;
signIn: (retryCount: number) => void;
customConstant: "constant";
get fullName(): string;
set username(name: string);
}
Looks similar to the type
definition above? Now let's look at the true power of interfaces
: they can be extended, used with Generics
, and even used with classes.
// Extend an interfaceinterface Animal {
leg: number;
}interface Dog extends Animal {
bark(): void;
}const dog: Dog = {
leg: 4,
bark: () => console.log("Woof!"),
};// Genericsinterface APICall<Response> {
data: Response;
}const api: APICall<string> = {
data: "Hello",
};
Classes
Classes in TypeScript work very similar to JavaScript, with small differences. You have to declare the types of the properties in the class, the ability to combine interfaces, add access specifiers, and create abstract classes.
// Implement an interfaceinterface IStorage {
data: string;
}class Store implements IStorage {
data: string; constructor(d: string) {
this.data = d;
}
}// Access Specifiersclass User {
// default specifier for data & methods is public
public id: string;
private secret: string = "super secret string"; constructor(id: string) {
this.id = id;
}
}// Abstract classesabstract class Animal {
abstract getName(): string;
}class Dog extends Animal {
getName() {
return "Dog";
}
}
Wrapping Up
Give yourself a pat on the back! You’ve now know TypeScript.
Finally, my disciple, you are ready to start writing TypeScript code. Go ahead and try it out! It is a bit difficult to get started, but once someone does, I have never heard them going back to JavaScript before!
Happy Developing!
Finding personal finance too intimidating? Checkout my Instagram to become a Dollar Ninja
Follow me for weekly new tidbits on the domain of tech
Need a Top Rated Front-End Development Freelancer to chop away your development woes? Contact me on Upwork
Want to see what I am working on? Check out my Personal Website and GitHub
Want to connect? Reach out to me on LinkedIn
I am a freelancer who will start off as a Digital Nomad in mid-2022. Want to catch the journey? Follow me on Instagram