TypeScript Basics
A beginner guide to TypeScript covering static types, variables, functions, and the compiler workflow.
TL;DR
- Annotate variables with primitive types like
stringandnumber. - Define typed function parameters and explicit
voidor return shapes. - Run
tscto compile typed code down to clean JavaScript.
Primitive Types
stringRepresents textual data wrapped in quotes or backticks.
const username: string = 'Alex';
const greeting: string = `Hello, ${username}`;numberHandles integers, floating-point decimals, and special numeric values.
let count: number = 42;
const price: number = 19.99;
const hex: number = 0xff;booleanStores binary true or false values for conditions.
let isComplete: boolean = false;
const hasAccess: boolean = true;unknownRepresents any value safely by requiring type checks.
let rawInput: unknown = '{"id": 1}';
if (typeof rawInput === 'string') {
console.log(rawInput.trim());
}Variables and Arrays
Type InferenceInfers the type automatically from the assigned value.
let score = 100; // inferred as number
// score = 'high'; // Error: Type 'string' invalidArray SyntaxDeclares typed collections with square brackets.
const scores: number[] = [85, 92, 78];
const names: Array<string> = ['Ada', 'Linus'];Tuple TypesDefines fixed-length arrays with specific element types in order.
let record: [number, string] = [1, 'Active'];
record = [2, 'Pending'];readonly modifierPrevents mutation of array elements after creation.
const values: readonly number[] = [1, 2, 3];
// values.push(4); // Error: push does not existFunctions and Parameters
Typed ParametersEnforces type safety on function inputs and outputs.
function add(x: number, y: number): number {
return x + y;
}Optional ParametersMarks arguments that can be omitted with a question mark.
function greet(name: string, title?: string): string {
return title ? `${title} ${name}` : name;
}Default ParametersProvides fallback values for omitted function arguments.
function multiply(a: number, factor: number = 2) {
return a * factor;
}void ReturnSignifies that a function returns no meaningful value.
function logEvent(message: string): void {
console.log(`[LOG]: ${message}`);
}Compiler and Config
tsc --initGenerates a starter tsconfig.json file in your project.
# Initialize TypeScript config
npx tsc --inittsc --watchCompiles project files automatically when changes are saved.
# Start watch mode
npx tsc --watchstrict modeTurns on all strict compiler checks simultaneously.
{
"compilerOptions": {
"strict": true,
"target": "ES2022"
}
}Tips
- Rely on TypeScript type inference when assigning values to
constorletvariables to keep your codebase expressive and clean. - Enable the strict flag in
tsconfig.jsonearly to prevent subtle runtime bugs and missing null checks.
Warnings
- Avoid using the
anytype because it completely disables compile-time type checking for that value. - Remember that TypeScript type annotations vanish at runtime, meaning you still need
typeofchecks to validate dynamic API responses.
In Practice
Demonstrates typed variables, arrays, optional parameters, and return types in a practical cart calculation.
- Declare a tuple and typed arrays to hold product identifiers and prices.
- Write a typed function calculating totals with an optional tax parameter.
- Calculate discount adjustments using inferred numeric types.
- Return a formatted string ensuring type correctness at compile time.
const items: [string, number][] = [
['Notebook', 14.5],
['Gel Pen', 2.5],
];
function calculateCartTotal(
list: [string, number][],
taxRate: number = 0.08
): number {
const subtotal = list.reduce(
(sum, [, price]) => sum + price, 0
);
return subtotal * (1 + taxRate);
}
const total = calculateCartTotal(items);
console.log(`Total: $${total.toFixed(2)}`);FAQ
Install TypeScript with npm install -D typescript inside your project directory. Run npx tsc --init to generate a default tsconfig.json file. You can then run npx tsc to compile .ts files into standard JavaScript.
Both define object shapes, but interface supports declaration merging and is idiomatic for object-oriented designs. Type aliases (type) handle unions, intersections, primitives, and tuple types that interfaces cannot express.
Choose unknown whenever a value comes from an untrusted source like external user input or a network request. TypeScript requires narrowing or type checks before you can call methods on an unknown variable, whereas any bypasses all safety checks.
Variables declared with let can be reassigned, so TypeScript widens their type to general primitives like string. To retain an exact literal type, declare the variable with const or append the as const assertion.
let wide = 'hello'; // type: string
const narrow = 'hello'; // type: 'hello'