Technology · TypeScript
TypeScript Basics
A starter guide to TypeScript covering types, variables, and basic syntax for newcomers.
TL;DR
- 01Add static types to your JavaScript variables and functions.
- 02Catch bugs at compile time before code runs.
- 03Use the TypeScript compiler to convert to JavaScript.
Setup
- Install TypeScript globally with npm to get the
tsccommand.npm install -g typescript - Run
tsc --initto create atsconfig.jsonfile for your project.tsc --init - Save your code in files with the
.tsextension instead of.js. - Compile your TypeScript file by running the compiler with the filename.
tsc filename.ts - Run the generated JavaScript file with Node or in the browser.
Basic Types
- Use
stringfor text values like names, messages, or any words.const name: string = "Sam"; - Use
numberfor integers and decimals, since there is no separate float type.const age: number = 30; const price: number = 9.99; - Use
booleanfor true and false values in conditions and flags.const isActive: boolean = true; - Use
anyto disable type checking, but try to avoid it.let data: any = 42; data = "now a string"; // allowed - Use
unknownfor safer code when the type is not yet known.
Variables
- Declare typed variables with an annotation after the variable name.
let username: string = "Sam"; - Skip the annotation and let TypeScript infer the type from the value.
let count = 5; // inferred as number - Use
constfor values that never change, like config keys or fixed numbers.const MAX_RETRIES = 3; - Declare arrays using square brackets or the generic Array form.
const scores: number[] = [10, 20, 30]; const names: Array<string> = ["A", "B"]; - Use tuples for arrays with fixed types and length.
const point: [number, number] = [10, 20];
Functions
- Add types to parameters and a return type for full safety.
function add(a: number, b: number): number { return a + b; } - Use
voidas the return type for functions that do not return anything.function log(msg: string): void { console.log(msg); } - Mark optional parameters with a question mark after the name.
function greet(name?: string) { return `Hi ${name ?? "friend"}`; } - Set default parameter values directly in the function signature.
function multiply(a: number, b: number = 2) { return a * b; } - Type arrow functions the same way as regular functions for consistency.
Compiler
- Edit
tsconfig.jsonto control how the TypeScript compiler builds your code. - Enable
"strict": trueto turn on all strict type-checking options at once.{ "compilerOptions": { "strict": true, "target": "ES2022" } } - Use
"target"to choose which JavaScript version the compiler outputs. - Run
tsc --watchto recompile files every time you save changes.tsc --watch - Check the
outDirsetting to control where compiled JavaScript files are saved.
Tip: Let TypeScript infer types when the value is obvious to keep your code clean and readable.
Warning: Avoid the
anytype whenever possible, since it removes the type safety that TypeScript provides.