TypeScript — For Beginners

A Strongly Typed, Object Oriented, Compiled Language

Osha Groetz
8 min readMay 11, 2021
Learning TypeScript Along with an Academind Tutorial

TypeScript is a strict syntactical superset of JavaScript. It takes the JS language and adds new features and advantages to it. Browsers can’t execute TypeScript (neither can Node.js), so Typescript acts as a compiler that you run over your code to compile TypeScript code to JavaScript. It makes JS easier to use by adding ‘types’ to JavaScript while cutting down runtime errors by catching errors earlier during development.

TypeScript adds Types! and compiling down TypeScript allows the use of modern JS features in older browsers, Interfaces & Generics non-JS features available, usage of features like Decorators, as well as configuration options.

Install TypeScript

First, if you don’t already have it installed, install Node.js, by visiting https://nodejs.org/en/ and download the latest stable version of Node.js. After you have installed node, install the node package TypeScript with terminal command: npm i typescript . This packages installs the compiler that allows you to write TypeScript and then does the work converting it to JavaScript for you. To run the compiler, you’ll use command: npx tsc .

Application Set Up

Change directories into the folder where you’d like to set up you application. In the terminal type the following command to set up the program: mkdir <app name> . Then after you cd into this folder that you just made, type terminal commands: touch index.html and touch .gitignore . Open up your application in your text editor (for me the command is: code . ).

To open your application in the browser, the quick command is: open index.html . Right away, we can set up a new file in the root folder called app.ts . To start the compiler (which will auto-generate the app.js file — NOTE: don’t have the two files open at the same time, or you’ll get errors!!!), run: npm tsc app.ts .

To check if your up and running correctly and that your compiler is working, add this to your app.ts file and run the compiler with the code just above:

app.ts

To create the package.json file for our dependencies, run terminal command: npm init -y . Install lite-server, with command: npm install --save-dev lite-server . From the lite-server npm page: “[a] development only node server that serves a web app, opens it in the browser, refreshes when html or javascript change, injects CSS changes using sockets, and has a fallback page when a route is not found.” In the package.json file add another script (line 8):

package.json

With the lite-server package, you now have access to running the index.js file in development with the simple command: npm start . Now, you won’t have to continually stop and start your server when there are changes to your code.

npm start — lite-server

You’ll still need to use the terminal command: npm tsc app.ts to compile your .ts file.

  • **Note: Add the code: node_modules to your .gitignore file before adding this application to github, so that the node_modules folder is not included in your git merge.

Core Types

Javascript has built in types, TypeScript gives us more types, and also gives us the ability to write custom types.

Javascript already knows these types:

  • number (no special types for integers, floats, etc.)
  • string (text with single or double quotes or backticks)
  • boolean (true / false)

Example of how to start using type specifications and the immediate errors the extra sanity check of TypeScript will throw throughout development (only!) when types aren’t specified or an input is invalid against the type:

app.ts

The terminal will also throw the error when trying to compile:

  • **Note: Typescript only helps us during development it doesn’t change JS to work differently at runtime bc browsers have no built in TypeScript support.

Javascript is dynamically typed. Dynamically-typed languages are those where the interpreter assigns variables a type at runtime based on the variable’s value at the time.⁴ TypeScript is statically typed: define types of variables and parameters during development.

Typescript has these core types:

  • number
  • string
  • boolean

Example of function using number, string and boolean types:

app.ts

Line 11: ‘const number1 = 5’ doesn’t need to be explicitly written as ‘const number1: number = 5;’ because of type inference, unless you are initializing the constant without a value → ‘let number1: number’ and then later in the code → ‘number1 = 5’ .

  • object

Example of object in TypeScript:

Typescript knows that nickname was not an attribute expected and throws the error ‘does not exist’.

If we hover over ‘person’ after the console.log, TS knows the attributes it’s expecting and what type they should be by type inference (what is shown is called object type):

  • array

Array type can be flexible or strict (re: element types).

hobbies → type: array
  • tuple

Fixed length, fixed type array. Beware that TypeScript can not catch using the method .push on tuples. Length is enforced explicitly, but not with .push().

tuple type
  • enum

enum { NEW, OLD } → enumerated list with human readable labels. Enum assigns labels to numbers. ***Note: when you define the enum (on the example below enum Role), the optional values all inherently get assigned a number (ex: Role.ADMIN = 0):

enum type

You can specify a value to start your enum count at, like so:

enum Role { ADMIN = 5, READ_ONLY, AUTHOR }; → then TypeScript would infer that Role.READ_ONLY = 6 . Also, you could assign them to whatever you choose → enum Role { ADMIN = ‘ADMIN’, READ_ONLY = 100, AUTHOR = 200 };

  • any

Avoid any whenever possible. Checks are too loose and ends up bringing you back to vanilla JS. Try to explicitly set types if/when you can.

Union Type

With union types, TypeScript allows us to use more than one data type for a variable or a function parameter:

union types

Literal Types

literal types

Union Type Combined with Literal Type:

Creating a Type Alias for Union Type:

Void Type

The function doesn’t have a return statement, even though it successfully completes and console.logs, for example, but there is no return value.

Undefined Type

Function Type

Callbacks and Function Types

Unknown Type

Unknown, although a lot like the any type, is more restrictive.

Never Type

Never is another type that functions can return.

The TypeScript Compiler

The TS compile command: npx tsc <file-name>.ts is fine for working on small projects, with small files, but not feasible for large projects. It is possible to configure the compiler.

Watch mode: tell TypeScript to watch our .ts file and whenever there are any changes, TS should re-compile the file. Type in terminal command: npx tsc app.ts --watch. ***Don’t quit watch mode while developing. ***Watch mode not great when you have more than 1 .ts file (which is more often then not).

Watch the entire project and re-compiles when any file changes: type terminal command: npx tsc --init . This creates a tsconfig.json file. Now you can run npx tsc in the terminal. It will create .js files for all of your .ts files and compile them all. To watch all the falls: npx tsc --watch .

tsconfig.json file:

You can add in files to exclude from compiling:

You can add in a wildcard exclusion (exclude anything that ends in .dev.ts , for example):

Or: “**/*.dev.ts → ignore any file in any folder with that pattern.

Always good to exclude node_modules. It is automatically excluded as a default setting, but if you do set up the “exclude”, include it as a line item to exclude, otherwise it won’t:

Conversely, you can set include, and the compiler will only compile the files (or folders) you specify:

Compiler Options (tsconfig.json):

  • “target”: “es5” → set by default. Which JS version you want to target. Delete es5 and press control space to see other versions that are available.
  • “lib” → specify which js library files/features to include in compilation
  • “sourceMap”: true → allows you to see the .ts files in the ‘Sources’ tab in the browser inspector
  • “outDir” → tell the program where the .js files (output files) should be stored in the file system. (ex: “./dist” for .js files when we store our .ts files in the ‘src’ folder)
  • “rootDir” → set to “./src” telling TypeScript to only look in the src folder for compiling
  • “removeComments” → can set to true and comments in .ts file won’t show up in .js file → making program smaller
  • “noEmitOnError” → not in the code, but can add. If you want to compile, despite having an error, set to false. True → problematic files will not be generated (it won’t actually compile any of the files if one has an error). Recommended to include and set to true.
  • “strict” → enables all strict TypeScripting options
  • “noImplicitAny” → ensures that we have to be clear about the params, we don’t want TypeScript to infer the params, fix errors by declaring type on your params.
  1. Typescript Course for Beginners 2021 | Academind | “https://www.youtube.com/watch?v=BwuLxPH8IDs
  2. Typescript | “https://www.typescriptlang.org/
  3. Typescript | “https://www.npmjs.com/package/typescript
  4. Dynamic Typing | Mozilla | “https://developer.mozilla.org/en-US/docs/Glossary/Dynamic_typing

--

--

Osha Groetz

Software Engineer. React, Javascript, Typescript, HTML, CSS, Ruby, Ruby On Rails