Prerequisites:
- Node.js installed (version 14 or higher)
- Basic knowledge of JavaScript
Introduction
TypeScript is a statically-typed superset of JavaScript that adds optional type annotations and compiles to plain JavaScript, enabling developers to catch errors at compile-time rather than runtime.
info
TypeScript is called a superset of JavaScript because every valid JavaScript program is also a valid TypeScript program, but TypeScript adds additional features (like types) on top of JavaScript's existing syntax.
function add(a: number, b: number): number {
return a + b;
}
const goodExample = add(5, 5);
const badExample = add("5", 5); // will give an errorWhat'll you learn
By the end of this tutorial, you’ll be able to:
- Understand what TypeScript is and why it’s a superset of JavaScript
- Install and use the TypeScript compiler (
tsc) to turn.tsfiles into plain JavaScript - Set up and run TypeScript files directly with
tsx, including watch mode for rapid iteration - Declare variables with basic built-in types (
number,string,boolean,null,undefined) - Leverage TypeScript’s type inference to avoid redundant annotations
- Annotate function parameters and return values for safer APIs
- Recognize when (and when not) to use the
anytype to preserve type-safety - Apply these essentials in a real project so you catch errors at compile-time rather than in production
Your First TypeScript code
Follow these steps to create your first TypeScript code.
Open your Terminal and install TypeScript.
npm install -g typescriptAfter you installed it, create a file named index.ts (this can be any name you want). Add the following code:
let message: string;
message = "Hello World!";
console.log(message);Compile the TypeScript file to Javascript using tsc index.ts
As you'll see a new index.js file is compiled.
index.ts
index.js
let message;
message = "Hello World!";
console.log(message);More elegant set-up with tsx
tsx is a minimal command-line tool that runs TypeScript files directly. It compiles code in memory using an optimized compiler and launches it with Node.js, removing the need for a separate build step.
tsx works out of the box with sensible defaults. A custom tsconfig.json can be added at the project root to override those defaults.
Add tsx as a development dependency.
npm install --save-dev tsxExecute it without a prior build step.
npx tsx index.tsAutomatically restart on file changes.
npx tsx --watch index.tsinfo
Simplify usage by adding scripts to package.json.
npm run dev for rapid iteration.index.ts
package.json
{
"scripts": {
"dev": "tsx --watch index.ts",
"start": "tsx index.ts"
}
}Introduction to TypeScript Types
A list of essential TypeScript types:
number– Represents numeric values, both integers and decimals (e.g.42,3.14).string– Text data enclosed in single or double quotes (e.g."Hello, world!").boolean– Logical values:trueorfalse.null– An explicit “empty” or “no value” assignment.undefined– The default value of a declared but uninitialized variable.any– Disables type checking, allowing any value.void– Indicates the absence of a value, typically used as a function return type when nothing is returned.Array<T>(orT[], e.g.number[],string[]) – A list of values all of the same typeT.object– A non-primitive type; any value that isn’tnumber,string,boolean,null, orundefined.
Type assignment
You can explicitly declare a variable’s type using a colon:
let userName: string
userName = "Alice"
Now userName must always hold a string. If you try userName = 123, TypeScript will flag an error before you run the code.
Avoid redundant annotations when the initializer already makes the type clear.
let userName: string = "George"let userName = "George"Type inference
When you initialize a variable without an explicit type, TypeScript infers it from the value:
let userAge = 38
Here userAge is inferred as number. Later assignments must match that inferred type:
userAge = 40 // OK
userAge = "forty" // Error: Type 'string' is not assignable to type 'number'
Typing Function Parameters and Return Values
Always annotate each parameter. A default value lets TypeScript infer that parameter’s type. The return type is inferred from what you return.
function add(a: number, b: number = 5) {
return a + b
}
const sum = add(10, 20)
amust be anumberbdefaults to5, so it’s anumbersumis inferred asnumber
info
You can add an explicit return type (: number) after the parameters if you want extra clarity, but it’s optional when inference is clear.
The any Type
The any type turns off all type checking for a variable. Use it only when you genuinely cannot know a value’s type ahead of time:
let data: any = 36
data = "now a string"
data = false
data = {}
data = []
warning
Overusing any negates TypeScript’s safety benefits, making your code behave like plain JavaScript.
- Use
anyonly when absolutely necessary. - Narrow
anyto a more specific type as soon as you understand the data. - Document why
anywas required in that context.
Conclusion
With TypeScript installed globally and tsx introduced for direct execution and watch-mode compilation, you have elevated a plain JavaScript workflow into a statically typed environment that detects errors before they reach production.