TypeScript Tutorial

TypeScript Algorithms

sort, find, filter, and reduce work on arrays. Type the callback so the compiler checks the item.

Methods on the array, typed callbacks

C++ algorithms take two iterators: v.begin() and v.end(). TypeScript puts the same jobs on the array: sort, find, filter, reduce. You pass a function. Annotate that function’s parameter so tsc knows each item is a number (or astring, or your type).

The array-methods chapter introduced map, filter, and reduce. This page adds sort and find, and types every callback on purpose.

sort rearranges the array

sort changes the array in place. For numbers you must pass a comparator. The default sort converts values to strings, so 10 would come before 2. Return a negative number whena should come first.

Example

const temps: number[] = [18, 7, 21, 12, 9];
temps.sort((a: number, b: number) => a - b);
console.log(temps.join(" "));

Output is 7 9 12 18 21. a - b is ascending. b - a would be descending. After the call, temps itself is sorted. There is no separate copy unless you slice first.

Open this at /typescript/try with Try it in TypeScript. Remove the comparator and run again: string order is not numeric order.

find locates one value

find walks the array until the callback returns true. It returns that element, orundefined if nothing matches. Check the result before you use it. Type the item so the predicate can compare numbers, not any.

Example

const lots: number[] = [11, 42, 8, 19, 5];
const found: number | undefined = lots.find((n: number) => n === 42);
if (found === undefined) {
  console.log("missing");
} else {
  console.log("found " + found);
}

Output is found 42. Change 42 to 99 and the program printsmissing. find stops at the first match; it does not count the rest.

filter and reduce with typed items

The callback’s first parameter is one element. Write (n: number) (or your element type). Then a typo such as n.toUpperCase() is a compile error, not a crash later.

Example

const rolls: number[] = [3, 1, 3, 3, 6, 3];
const threes: number[] = rolls.filter((n: number) => n === 3);
const total: number = rolls.reduce((sum: number, n: number) => sum + n, 0);
console.log("threes: " + threes.length);
console.log("sum: " + total);

Output is threes: 4 then sum: 19. filter returns a new array.reduce returns the seed plus every element. A missing value in filter yields an empty array, not an error.

Type the callback

CallCallback itemReturns
sorttwo elements to comparevoid; rearranges in place
findone elementthe item, or undefined
filterone elementa new array of matches
reduceaccumulator and one elementthe running total

Inference often fills n: number in for you when the array is already number[]. Writing the annotation still documents the contract and catches a mismatched array type at the call.

Write a loop only when you must

A hand-written for that finds a max or a sum is fine while you learn. Once the work is “sort this” or “keep these,” prefer the named method. Next: arrow functions, the syntax those callbacks already used.

FAQ: TypeScript Algorithms

Common questions about this page.

What is the StudyGrid TypeScript tutorial?

The StudyGrid TypeScript tutorial follows the same chapter rhythm as C++: syntax, types, input, loops, functions, classes, generics, maps, and lambdas. Each chapter has copy-and-run examples.

Should I run typescript algorithms examples locally for better learning?

Yes. Use the browser editor on StudyGrid for a quick check, then Download the example and run it on your computer. Local runs show real errors and the real toolchain, which is one of the fastest ways to learn typescript algorithms in this TypeScript TypeScript lesson (TypeScript Algorithms).

Is the TypeScript editor the same as Try Python or Try C++?

No. Try TypeScript type-checks with tsc at /typescript/try and shows stdout plus compiler messages. Try Python stays at /try. Try C++ stays at /cpp/try. TypeScript lessons never open those editors.

Do I need to install a compiler to learn TypeScript?

No. Open a chapter, click Try it in TypeScript, and compile in the browser. You can also download a .ts file and compile locally with tsc.

Where should I start the TypeScript tutorial?

Start at TypeScript Intro, then Get Started and Syntax. After the first program, continue to output, variables, and if-else. After classes, open TypeScript Examples, then generics, Map, and arrow functions. Use Next at the bottom of each chapter.

Is the TypeScript tutorial free?

Yes. The TypeScript workshop on StudyGrid (studygrid.in) is free: dashboard, chapters, and the compile-and-run editor.