Learning TypeScript — Installation & Basic Types

Image for post
Image for post
Photo by David Klein on Unsplash

TypeScript as a Compiler

TypeScript is a source-to-source compiler which compiles to JavaScript in the end. Note that it will be JavaScript that will run in the backend and frontend of your applications and not TypeScript which aids in static type checking only.

Image for post
Image for post
TypeScript compiles to JavaScript, more specifically ES3 according to the docs.

Installation

Assuming that you use npm, you can download TypeScript as a dev dependency using the following command:

npm install typescript --save-dev
npx tsc
{
"compilerOptions": {
"module": "CommonJS", // Default is CommonJS for ES3 or ES5, and ES6 for ES6 or higher
"target": "ES2017",
"outDir": "lib", // output directory
}, "include": ["src"] // inputs: specify list of files or folders}

Basic Types

For TypeScript, the language supports the same basic types as JavaScript and a few more which we will get to later.

Image for post
Image for post
TypeScript being a superset for JavaScript would have more types supported.

Boolean

Types that hold true or false values.

let isTrue: boolean = true;

Number

Represents all numbers which are either type number or bigint. Supports other numeral systems such as hex and binary.

let decimal: number = 10;
let binary = 0b101; // 5
let hex: number = 0x9D2; // 2514
let big: bigint = 100n;

String

For textual data with single or double quotes surrounding the data. Also supports template literals.

let name: string = 'Bryan';
let language: string = "JavaScript";
let sentence: string = `Hi, my name is ${name} and I think ${language} is great!`

Array

Arrays are list-like objects which are ordered. They can be expressed with the types within the array followed by [] or via generic array type.

let list1: number[] = [1, 2, 3];
let list2: Array<number> = [1, 2, 3]; // Generic array type

Tuple

Arrays with fixed number of elements. The types within the tuple are known and do not have to be the same.

let tuple: [string, number] = ['hi', 123];
tuple = [123, 'hi'] // Error

Enum

This data type gives names to numeric values. It is essentially creating an object and assigning the numeric value to a value and vice versa for two-way mapping.

enum Languages = {
javascript, // default value assigned is 0
typescript, // 1
coffeescript, // 2
}
let favLanguage: Languages = Languages.typescript; // 1
enum Languages = {
javascript = 10,
typescript = 15,
coffeescript,
}
let notFavLanguage: Languages = Languages.coffescript; // 16 without any value assignment

Unknown

A type that is used for when we are unsure of the value and do not want to intentionally accept any value (see any below for a type that does).

let notSure: unknown;
notSure = 123; // Could be a number
notSure = true; // Could be a boolean even
let notSure: unknown;
notSure = 2;
if(typeof notSure === 'string') {
const isString: string = notSure; // After checking if it is a string, we know for sure it is of type "string". Same for below.
}
if(typeof notSure === 'number') {
const isNumber: number= notSure; // Value is 2
}

Any

A type that accepts all values. Useful for when not all type information is available or type declaration is impractical as it will take too long. TypeScript will not type check variables with the any types.

let anything: any = 4;
anything.pop() // Ok
anything.toFixed() // Ok. Works but TS does not check if it does
anything.a.b.c.d.whatever // Ok. Works too as TS does not check.

Void

Opposite of any and the absence of any types. You can only assign undefined or null (only if --strictNullChecks is not specified).

let itIsVoid: void = undefined; //Ok
itIsVoid = null; // Ok. only in non-strict null check mode

Nulls and Undefined

These types refer to themselves respectively. Not that much useful.

let a: null = null; // Ok
a = 123; //Error
let b: undefined = undefined //Ok
b = 123; // Error

Never

Represents values that never occur at all and does not have a reachable endpoint.

function error(message: string): never {
throw new Error(message);
}
function error2(message: string): never { // inferred type is never
throw new Error(message);
}
function infiniteLoop(): never { // does not reach completion
while(true) { }
}

Object

Refers to any non-primitive types which are number, string, boolean, bigint, symbol, null, or undefined. You will not need this in most cases.

let a: object = {}; // Oka = []; // Ok
a = null; // Error
a = '123'; // Error
a = 123; // Error

Type Assertions

Type assertions can also be made with the as syntax which allows you to arbitrary assert a type and take responsibility for it.

let notSure: unknown;
let isNum: number = (notSure as number) + 1; // Ok
let notSure2: unknown;
let isNum2: number = notSure2 + 1; // Error as it is unknown

Conclusion

In this post, we were introduced to what TypeScript is and how it is essentially just JavaScript in the end. Next, we went on to how to install the package locally and what commands to run your .ts file compilations. A tsconfig.json file can also be used to customize how you would like your TypeScript to be compiled. Finally, we looked into the basic types and observed that most of the added types are used in the static checking compilation phase for TypeScript. The other new types, Enum and Tuple, are abstractions of JavaScript which compiles to specifically mapped objects(two-way between keys and values), and arrays with definite lengths and types.

I have a passion for coding.

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