Skip to content

Chapter 3 of 8

Functions & Collection Types

TypeScript supports multiple ways to express collections of values. Arrays can be written using either bracket syntax, such as let numbers: number[] = [1, 2, 3];, or the generic Array<number> notation. Both forms accept a single uniform type, but heterogeneous data is better expressed with tuples, which are fixed-length arrays whose positions each have a specific type. An example is let pair: [string, number] = ["age", 30];, where the tuple enforces both length and the ordering of types.

Enums provide named constants that improve readability over magic numbers or scattered strings. By default, a numeric enum such as enum Color { Red, Green, Blue } assigns zero-based numeric values, but string-based enums are equally supported. Enums group related values into a single, easy-to-reference namespace and let integrated development environments offer autocomplete suggestions.

Functions are typed by annotating parameters and return values, as in function add(a: number, b: number): number { return a + b; }, and arrow functions follow the same conventions. Parameters can be made optional with ?, in which case they default to undefined when omitted, while default parameters supply a fallback value that activates when no argument is passed. Rest parameters use the spread syntax with an array type, like function sum(...numbers: number[]): number, collecting any remaining positional arguments into a single array for the body to work with.

All chapters
  1. 1Introduction to TypeScript & Setup
  2. 2Basic Types & Type System Fundamentals
  3. 3Functions & Collection Types
  4. 4Interfaces, Type Aliases & Object Shapes
  5. 5Classes & Object-Oriented Programming
  6. 6Generics for Reusable Code
  7. 7Modules & Advanced Type-Level Features
  8. 8Strict Mode & Interoperability with JavaScript

Drill it

Reading is not remembering. These come from the Typescript Essentials deck:

Q

What is TypeScript?

TypeScript is a statically typed superset of JavaScript developed by Microsoft that compiles to plain JavaScript code. It adds optional static typing, interface...

Q

How does TypeScript relate to JavaScript?

TypeScript is a superset of JavaScript, meaning all valid JavaScript code is also valid TypeScript. TypeScript code is transpiled to JavaScript, allowing it to...

Q

How do you install TypeScript?

Install TypeScript globally using npm install -g typescript or locally as a dev dependency with npm install typescript --save-dev. Verify installation with tsc...

Q

What is the TypeScript compiler command?

The TypeScript compiler is invoked with tsc. Use tsc file.ts to compile a single file or tsc to compile based on tsconfig.json.