Typescript overview

Jeff P
4 min readFeb 21, 2024

TypeScript is a programming language developed and maintained by Microsoft. It is a superset of JavaScript, meaning that any valid JavaScript code is also valid TypeScript code. TypeScript adds optional static typing to JavaScript, which can help catch errors early through type checking during development. The number one reason for using TypeScript is that it provides static type checking, allowing developers to check the type of their variables, functions, and objects at compile time. This helps catch errors early in the development process, before the code is run.

Installation

npm i -g typescript

NOTE: With Next.js typescript is already enabled. You can also make it available with vite.

Creating a config file

You can create a congifg file by running the following from the command prompt

tsc --init

This will create a tsconfig.json file

There are things you can specify in this file which will affect the way typescript is compiled (using “tsc” in the command prompt) as ultimately when typescript gets compiled, it gets compiled to regular JavaScript.

Usage

In regular JavaScript, we might do something like this:

// index.js file

let id = 5;

Whereas in typescript, we’d declare the variable type:

// index.ts file

let id: number = 5;

Now the fact that we’ve created an index.ts file means that we don’t actually have to make the declaration…. this would still be valid:

// index.ts file

let id = 5;

However, if we then went to try to re-assign this to a string, typescript would flag it!

// index.ts file

let id = 5;

id = "Bob";

If you want the let to be re-assignable to anything, you can declare it as “any”

let myvariable: any = "Bob";

myvariable = 10;
myvariable = true;

Arrays

If you want an array to only contain numbers, you would do this:

let myarray: number[] = [1,23,4,5,77];

again, use “any” if you want the array to be mixed:

let myarray: any[] = [1,"John",4,true,77];

If you want the array to have a specific sequence of types, you specify them in the brackets…

let myarray: [number, string, number, boolean] = [1,"John",4,true];

You can also specify an array of pre-defined tuples. For example:

let employee: [string, number][] = [
["John", 4],
["Chris", 17],
["James", 33],
["Mark", 18]
];

Unions

Unions are where you allow more than one type to be allowed. For example:

let id: number | string = "bob";

id = 22;

Enums

Enums are specifically designed for defining a set of named constants, often used for a finite set of options (like days of the week, directions, etc.)

IF you define an Enum in typsecript, each value will be assigned a value by default. For example:

enum direction {
Up,
Down,
Left,
Right
};

Here, “Up” would be assigned a default value of 0, and so on.

In typescript, you can alter this by doing the following:

enum direction {
Up = 1,
Down,
Left,
Right
};

By doing this, Up will now be defined as 1, Down will be 2, and so on.

You can also define enums as strings:

enum direction {
Up = "Up",
Down = "Down",
Left = "Left",
Right = "Right"
};

Objects

You can declare types as follows:

const user: {
name: string,
id: number
} =
{
name: "Bob",
id: 12
};

Another (arguably cleaner) way of achieving the same thing would be as follows:

type User = {
name: string,
id: number
};

const user: User {
name: "Bob",
id: 12
};

Functions

With functions, we specify the input types, as well as the return value type

function addNum(x: number, y: number): number {
return x + y;
}

For functions that don’t have a return value, they should be marked “void”

function logger(message: string): void {
console.log(message);
}

logger("hello");

Interfaces

You normally use interfaces with objects

interface User {
name: string,
id: number
};

const user: User {
name: "Bob",
id: 12
};

With interfaces, you can have optional properties

interface User {
name: string,
id: number,
age?: number
};

const user: User {
name: "Bob",
id: 12
};

You can also make properties “readonly” which means you won’t be able to re-assign them.

interface User {
name: string,
readonly id: number,
age?: number
};

const user: User {
name: "Bob",
id: 12
};

// allowed
const user.name: "Dave";

// not allowed
const user.id = 4;

ES6 Classes

The following is an example demonstrating how TypeScript can be used with ES6 classes, including type annotations, constructors, methods, and property access modifiers like public, private, and protected. This example defines a simple Person class with a constructor and a method to display the person's information:

class Person {
private firstName: string;
private lastName: string;
public age: number;

constructor(firstName: string, lastName: string, age: number) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

public getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}

public describe(): void {
console.log(`Name: ${this.getFullName()}, Age: ${this.age}`);
}
}

class Employee extends Person {
private jobTitle: string;

constructor(firstName: string, lastName: string, age: number, jobTitle: string) {
super(firstName, lastName, age);
this.jobTitle = jobTitle;
}

public describe(): void {
super.describe();
console.log(`Job Title: ${this.jobTitle}`);
}
}

// Example usage:
const employee = new Employee('John', 'Doe', 28, 'Software Developer');
employee.describe();
// Output:
// Name: John Doe, Age: 28
// Job Title: Software Developer

using Typescript with create-react-app

npx create-react-app my-app --template typescript

--

--

Jeff P

I tend to write about anything I find interesting. There’s not much more to it than that really :-)