Mastering TypeScript Functions

When working with data in TypeScript, understanding how to manipulate arrays methods is crucial. Whether you’re building APIs, cleaning data, or transforming responses, JavaScript offers powerful array functions that help you write clean, expressive, and bug-resistant code.

In this post, we’ll explore the most important TypeScript methods you need to master as a senior developer, using clear explanations and practical examples.

TypeScript array methods

2. map: Transform Every Element

What it does: Creates a new array with the results of applying a function to each element.

const numbers: number[] = [1, 2, 3];
const doubled: number[] = numbers.map((n: number): number => n * 2); // [2, 4, 6]

Best practice:

  • Always return a value inside map.
  • Avoid side effects (pure functions).

4. Typescript functions reduce Turn an Array into One Value

What it does: Applies a function against an accumulator and each element to reduce the array to a single value.

const values: number[] = [1, 2, 3, 4];
const sum: number = values.reduce((acc: number, val: number): number => acc + val, 0); // 10

Best practice:

  • Always provide an initial value.
  • Use for totals, grouped counts, merging objects, etc.

Advanced example:

interface Order {
  id: number;
  amount: number;
}

const orders: Order[] = [
  { id: 1, amount: 100 },
  { id: 2, amount: 50 },
  { id: 3, amount: 75 }
];

interface Summary {
  count: number;
  total: number;
}

const summary: Summary = orders.reduce(
  (acc: Summary, o: Order): Summary => ({
    count: acc.count + 1,
    total: acc.total + o.amount
  }),
  { count: 0, total: 0 }
);

6. some / every: Test for Logic

some: Returns true if any element passes a condition.

const values: number[] = [1, 3, 5];
const hasLarge = values.some((v: number): boolean => v > 2); // true

every: Returns true only if all elements pass the condition.

const allPositive = values.every((v: number): boolean => v > 0); // true

Best practice: Great for validation checks or quick tests.

8. Object Entries, Keys, and Values

These work on objects but are extremely useful:

const user = { id: 1, name: "Alice" };
const keys: string[] = Object.keys(user);
const values: (string | number)[] = Object.values(user);
const entries: [string, string | number][] = Object.entries(user);

Best practice: Combine with map, filter, and reduce to iterate over objects.

Conclusion

Mastering these Typescript functions will level up your coding and make your data transformation logic concise, testable, and readable. These are tools you’ll reach for daily, especially when working with APIs, large datasets, or functional pipelines.

Take time to play with examples. Use TypeScript functions to enforce shape and catch mistakes early.

Happy coding!

You Might Also Like

Leave a Reply