Getting Started
Video Lecture
Section | Video Links |
---|---|
Getting Started | |
Adding tsconfig.json | |
TSC Watch |
Overview
TypeScript is a tool to help you write type-safe JavaScript. JavaScript is a weakly typed language which means that types are assigned implicitly as they are used at runtime. While this can be considered a feature, it can be dangerous if your code needs to be treating types precisely at all times. Enforcing type safety ensures that all usage of the properties, functions and classes are consistent within your application and as a result makes your application more robust.
When writing TypeScript, it will appear in many ways very similar to JavaScript. TypeScript is a subset of JavaScript. So, you can write JavaScript in a TypeScript file first, but the IDE, VSCode in my case, will indicate many suggestions on how to modify your code to be more type safe.
In this next section on TypeScript basics, we will go through many concepts which may be JavaScript first, but you will see the TypeScript equivalent so that you can get a better understanding between the languages.
Create Our First TypeScript File
The first example is that we will create a basic TypeScript file that we will compile/transpile into JavaScript that Node.js will run.
Note
The terminology of whether TypeScript is compiling or transpiling is an ongoing argument that you can look up on the internet if you want to take part in it. I will use the term compile, since transpile is not currently a real word in the Oxford Dictionary, and TSC is called the TypeScript Compiler.
Go to the ./src
folder in your project and create a new file called test.ts
In that file add this script
1 2 3 4 5 6 7 |
|
Compile The TypeScript File Into JavaScript
Open the VSCode integrated terminal using the keys Ctrl+Shift+'
, or using the top menu Terminal --> New Terminal
.
In the project root folder type
tsc ./src/test.ts --outDir ./dist
Note
Remember that you don't need to use PowerShell. You can use Git Bash, Windows CMD prompt, or another terminal on your operating system. If you are using PowerShell in the VSCode integrated terminal, and you haven't modified the settings.json
as outlined in the last section, you may have gotten an execution policy error. You have the option to start the tsc
compilation process by using the tsc.cmd
option instead. E.g, tsc.cmd ./src/test.ts --outDir ./dist
So, now if you visit the ./dist
folder there will be a new file in it called test.js
. It will be almost identical to the ./src/test.ts
file that we just wrote and processed with TSC, but with the new file extension being .js
instead of .ts
and the TypeScript type annotations removed. I.e.,
1 2 |
|
becomes
1 2 |
|
The TypeScript version explicitly declares which type the bar
arguments must be when passed to the foo
function and that is a string
.
Warning
If you have ./src/test.ts
and ./dist/test.js
open in VSCode at the same time, you may see an error indicated saying that foo
and baz
have been re-declared in the other file. This happens when both files are open in the editor at the same time and your project doesn't have a tsconfig.json
indicating which folders are officially the "rootDir" and "outDir" folders of your project. This will be discussed and setup in the next section. In the meantime, you can close one of the files in the IDE to prevent VSCode from thinking that this is an error.
Run The Compiled JavaScript
We can now run this ./dist/test.js
using Node.js. So from your project root run,
node ./dist/test.js
You should get the output,
Hello, ABC
Note
On Windows, using either forward slashes /
or backslashes \
as folder and file separators is ok. So, while I have written node ./dist/test.js
in my documentation, I could also have written node .\dist\test.js
and executed it in PowerShell or Windows CMD, and it would still work. I prefer to use forward slashes in my documentation since backslashes may cause ambiguity in case of the backslash escape character functionality that can also be utilized when entering commands into a terminal.
Now, to see type safety in action, in the TypeScript file ./src/test.ts
change
let baz = 'ABC'
to
let baz = 123
and the VSCode editor will now indicate to you at design time, the error
Argument of type 'number' is not assignable to parameter of type 'string'
Warning
Don't forget to change the line back to let baz = 'ABC'
since we will use this file in the next section.
While passing a number to a function that expects a string in JavaScript may not always be a problem for you and will not throw a runtime error; by compiling our JavaScript from a TypeScript source file first it can protect us from those unforeseen potential problems that may occur when writing JavaScript code directly. This protection provided by writing TypeScript in the VSCode IDE/editor happens at design time, rather than at runtime when any problems caused could potentially have been much worse.
Remember that TypeScript is not intended to run in the final environment, such as in Node.js or in a web browser, but it is a tool that developers can use to help write type-safe and more robust JavaScript.
Adding tsconfig.json
Normally, it is best practice to create a tsconfig.json
file in the base of your TypeScript source folder in your project.
So, create a new file called tsconfig.json
in the ./src/
folder alongside the existing test.ts
./src/tsconfig.json
1 2 3 4 5 6 7 8 9 10 11 |
|
Your project structure should now resemble
|-- Design-Patterns-In-TypeScript
|-- dist
|-- test.js
|-- node_modules
|-- @types
|-- node (A folder including many *.d.ts files)
|-- src
|-- test.ts
|-- tsconfig.json
package.json
package-lock.json
Now you can compile your test.ts
into JavaScript by calling tsc
and indicating the tsconfig location which is the ./src
folder.
tsc -p ./src
To analyze this tsconfig.json
,
"strict":true
: The strict flag enables a wide range of type checking behavior that results in stronger guarantees of program correctness. I mainly use it to ensure that all class properties are either assigned when first declared, or in the constructor."target": "ES2015"
: ES stands for ECMAScript which is a documented JavaScript standard. TSC will produce JavaScript that matches the selected standard. Options are ES3, ES5, ES2015, ES2016, ES2017, ES2018, ES2019, ES2020, ES2021, ES2022 and ESNEXT. Each ES version introduces new core JavaScript functionality. I have chosen ES2015 since TSC won't compile earlier versions if the source TypeScript contains private identifiers. Visit https://en.wikipedia.org/wiki/ECMAScript for more information about the ES version differences."module": "CommonJS"
: In many of the code examples in the course, I am using ES6 import/export syntax. TheCommonJS
module setting will produce output that relies on the popularRequireJS
module loader that Node.js supports by default. This means that any JavaScript produced from TSC will work in Node.js in case your source TypeScript code contains any ES6 import commands."outDir": "../dist"
: This is the folder where the compiled JavaScript will be placed. Note that it has 2 dots indicating to go back/down one folder, and then up into thedist
folder. This is relative to therootDir
parameter discussed in the next line."rootDir": "./"
: This is the root directory of the TypeScript project containing all the*.ts
files, and not the project root directory which was referred to earlier that contains all the projects files including thesrc
,dist
,node_modules
,package.json
, etc. It is the folder that TSC should consider to be the root when compiling."moduleResolution": "node"
: Is the default, and describes the file finding resolution process in which TSC will find dependencies if and when they are referenced in any code."include": ["**/*.ts"]
: Indicates to compile all files it finds ending in.ts
in this and any sub folders relative to therootDir
setting within this sametsconfig.json
.
The sample tsconfig.json
I have provided is minimal and is ideal for this complete course when trying to execute the code examples using Node.js. On the internet you will find many TypeScript projects with varying tsconfig files all written specifically for the purpose of the particular project that they exist in.
Note
Now that you have a tsconfig.json
in your TypeScript source root, you can open both the ./src/test.ts
and ./dist/test.js
in the VSCode IDE and no errors describing duplicate declarations should occur.
For documentation on all the options that you can have in a tsconfig.json
file, visit https://www.typescriptlang.org/tsconfig
TSC Watch
Before running your compiled JavaScript in Node.js, you need to run your TypeScript source files through TSC.
This process of running tsc -p ./src
and then seeing the output in Node.js using node ./dist/test.js
for example, can be quite tedious if you need to keep typing the tsc
and the node
commands in turn for every change you make.
Instead, you can run TSC in watch mode, which will cause it to continue running and automatically compile and check any changes you make to the TypeScript source files, and then you open a second terminal that you can use specifically for executing the node
or other commands.
Run
tsc -p ./src -w
This will keep the first terminal running indefinitely while it watches and re-compiles any changes you make in the ./src
folder and sub folders.
Now open a second console/terminal, or use the split
option to open a second terminal to the right.
In the second terminal, you can now run your JavaScript, for example node ./dist/test.js
In the above image, the left pane is busy running tsc -p ./src -w
while the right pane is free to enter any manual commands as needed such as node ./dist/test.js
I advise to watch the video for this section to show how I do this if my description is hard to understand.