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.
Jump to section
Tips
- 01Let TypeScript infer types when the value is obvious to keep your code clean and readable.
Warnings
- 01Avoid the <code>any</code> type whenever possible, since it removes the type safety that TypeScript provides.
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.
FAQ
Run npm install -g typescript to install the compiler globally, then use tsc --init in your project folder to generate a tsconfig.json with sensible defaults. From there, run tsc to compile your .ts files to JavaScript.
Both can describe object shapes, but interface supports declaration merging and is generally preferred for defining object structures, while type is more flexible and can represent unions, intersections, and primitives. Use interface for class contracts and public APIs, type for everything else.
Mark a parameter optional with a ? suffix (e.g., name?: string), which makes it string | undefined inside the function. For defaults, use standard JavaScript syntax (name: string = 'guest'), which also makes the argument optional at the call site without the undefined type.
unknown is the type-safe alternative: you can assign anything to it, but TypeScript forces you to narrow the type before using it, preventing accidental runtime errors. Reach for unknown when you genuinely don't know the type upfront, such as parsing JSON or handling catch clause errors.
TypeScript widens literal values (e.g., let x = 'hello' becomes string, not 'hello') to allow reassignment. Use const instead of let to keep the literal type, or add as const to freeze an object or array's inferred types to their exact literal values.