A Typescript program needs to be transpiled to Javascript first, and it runs on Javascript runtimes such as Web browsers or Node.js/Deno.
Let's try creating a simple program using basic development tools.
- Prerequisite: Typescript development environment setup
Creating the First Program in Typescript
Although it's not absolutely necessary, it is best to use various modern development tools when you program in Typescript or modern Javascript. This holds true even when you only do frontend development.
Let's use node.js since that is the most popular tool at the moment.
$ mkdir first-program && cd $_
$ npm init -y
Wrote to /home/harry/Projects/codeandtips/code/typescript/first-program/package.json:
{
"name": "first-program",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC"
}
$ ls
package.json
Then, create a tsconfig.json file.
The easiest way to do this is just to copy it from an existing typescript project.
Otherwise,
you can create a new one using the tsc
command:
$ tsc --init
tsc --init
Created a new tsconfig.json with:
target: es2016
module: commonjs
strict: true
esModuleInterop: true
skipLibCheck: true
forceConsistentCasingInFileNames: true
You can learn more at https://aka.ms/tsconfig.json
$ ls
package.json tsconfig.json
You can use the generated tsconfig.json file as a starting template for any future ts projects.
$ cat > index.ts
console.log("the first time!")
^D
$ ls
index.ts package.json tsconfig.json
Although it is not required,
it is a convention to use names like index.ts
or main.ts
for the main script file.
The generated node.js package.json file uses index.js
as the main script name by default.
$ tsc
$ ls
index.js index.ts package.json tsconfig.json
Running tsc
command compiled all ts files in the current working directory
(or, based on how it is configured in the tsconfig.json file)
into javascript files.
$ cat index.js
"use strict";
console.log("the first time!");
In this example,
the only difference between the input typescript and output javascript file
is the extra line, "use strict";
.
In Typescript programs, everything is in the "strict mode" of Javascript.
Now you can run the generated JS program just like any other Javascript scripts. For example,
$ node index.js
the first time!
In a bigger project, the script section of the package.json file is typically modified to make compiling and running typescript programs easier. We will see some examples in later posts.
It is also conventional to include *.js
in the .gitignore file
in the typescript projects so that you don't check in the generated files into git.
C C++ C# Clojure Crystal D Dart Erlang F# Go Haskell Java Javascript Julia Kotlin Lua Python Rust Scala Swift