Learning TypeScript — Installation & Basic Types

Bryan W.
5 min readDec 2, 2020
Photo by David Klein on Unsplash

TypeScript is an extension of JavaScript that provides type checking functionality to the language. With TypeScript, you will be able to find catch errors during compile time instead of run time thus making it incredibly useful in the development process.

In this multi-part series, come join me as we discover the basics of TypeScript. The goal of writing these posts is to understand TS and explain it as simply as possible to my readers, assuming that they have a foundation in JavaScript.

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.

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

After, you can run the compiler with the following:

npx tsc

To customize how you can compile process of TypeScript, you might want to add a tsconfig.json file in your root directory. Here is an example of what it would have to get started. You may refer to the TsConfig Reference for more details.

{
"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.

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

From above, the initialization of tuple as [123, 'hi'] will throw an error at compile time because the types did not correspond to a string then number.

Another note about tuples, they are not actually immutable like the tuple type from python. You can change it’s value, and perform push() and pop() operations to it. See example from TS playground.

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

We see that the mapping of members within the enum type starts from 0. You can also change its starting point or assign all of them a number.

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

We can narrow the unknown type by using typeof . See below.

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.

--

--

Bryan W.

I have a passion for coding | Salesforce Developer