Introduction to TypeScript

Starting off with TypeScript

Adding Types to JavaScript — Part 1

Primitive Typing

const text: string;
const amount: number;
const loggedIn: boolean;

Type Inference

const text = "Hello, World!";
const amount = 1000;
const loggedIn = False;
const text = "A" // TypeScript infers text is of type string
const text: string | Array<string> = "A"

Array & Union Types

const primitive: string | number | boolean;
console.log(primitive.toUpperCase());      // <-- Type Error
if (typeof primitive === "string") {

The ANY Type

let obj: any = { x: 0 };// None of the following lines of code will throw compiler errors.
// Using `any` disables all further type checking, and it is assumed
// you know the environment better than TypeScript.;
obj(); = 100;
obj = "hello";
const n: number = obj;

Adding Types to JavaScript — Part 2

Adding Types to Functions

function add(x: number, y: number, message: string):number {
return x + y;

Creating Custom Types

type Point {
x: number;
y: number;
interface Point {
x: number;
y: number;
const point: Point// Equivalent to the below anonymous object type:const point: { x: number, y: number }
type leftAlignment = "left";   // Only permitted value is "left"type alignment = leftAlignment | "right" | "center"type validNum = -1 | 0 | 1type validInput = Point | validNum | 5    // Refer 'Point' def above

Adding Types to Classes

class PointAdder {
x: number;
y: number;

constructor(x: number, y: number) {
this.x = x;
this.y = y;
adder(a: number): number {
return this.x + this.y + a;
const test: PointAdder;

Next Steps



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ashok Khanna

Ashok Khanna

Masters in Quantitative Finance. Writing Computer Science articles and notes on topics that interest me, with a tendency towards writing about Lisp & Swift