Why typed functions matter in Typescript - Performance Analysis
We want to see how using typed functions affects the speed of running code.
Does adding types change how long the program takes as input grows?
Analyze the time complexity of the following code snippet.
function sumNumbers(numbers: number[]): number {
let total = 0;
for (const num of numbers) {
total += num;
}
return total;
}
const data = [1, 2, 3, 4, 5];
sumNumbers(data);
This function adds up all numbers in an array and returns the total.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each number in the array once.
- How many times: Exactly once for each item in the input array.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items; double the items, double the work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the input size.
[X] Wrong: "Adding types makes the function slower because it checks types at runtime."
[OK] Correct: Types in TypeScript are only for development and do not add extra work when the code runs.
Knowing how typed functions behave helps you write clear code without worrying about slowing things down.
"What if we changed the function to call itself recursively for each number? How would the time complexity change?"
Practice
Solution
Step 1: Understand the role of typed functions
Typed functions define what types of inputs they accept and what type they return, helping the developer know how to use them correctly.Step 2: Recognize the benefit of early error detection
By specifying types, TypeScript can catch mistakes before running the code, preventing bugs caused by wrong data types.Final Answer:
It helps catch errors early by ensuring correct input and output types. -> Option AQuick Check:
Typed functions = early error detection [OK]
- Thinking types speed up runtime
- Believing typed functions fix bugs automatically
- Assuming functions don't need inputs
Solution
Step 1: Check parameter and return types
The function should accept a number parameter and return a string, so the parameter must be typed as number and the return type as string.Step 2: Identify the correct syntax
function convert(num: number): string { return num.toString(); } correctly types the parameter as number and the return type as string. function convert(num): string { return num.toString(); } misses parameter type, C swaps types, and A misses return type.Final Answer:
function convert(num: number): string { return num.toString(); } -> Option BQuick Check:
Parameter: number, Return: string = function convert(num: number): string { return num.toString(); } [OK]
- Omitting parameter types
- Swapping parameter and return types
- Not specifying return type
function add(a: number, b: number): number {
return a + b;
}
const result = add(5, 10);
console.log(result);Solution
Step 1: Analyze function parameters and return
The function add takes two numbers and returns their sum as a number.Step 2: Calculate the result of add(5, 10)
Adding 5 and 10 gives 15, so result is 15 and console.log prints 15.Final Answer:
15 -> Option AQuick Check:
5 + 10 = 15 [OK]
- Thinking numbers concatenate as strings
- Expecting undefined return
- Assuming type error without mismatch
function greet(name: string): string {
return 'Hello, ' + name;
}
greet(42);Solution
Step 1: Check function parameter type
The function expects a string parameter named name.Step 2: Identify the call with wrong argument type
The call greet(42) passes a number, which conflicts with the string type.Step 3: Fix the call to match expected type
Changing greet(42) to greet('42') passes a string, fixing the type mismatch.Final Answer:
Change greet(42) to greet('42') to match string parameter. -> Option DQuick Check:
Parameter type mismatch fixed by passing string [OK]
- Ignoring type mismatch errors
- Removing return type instead of fixing input
- Changing parameter type without reason
Solution
Step 1: Understand the input types needed
The function must accept either string or number, so union type string | number is required.Step 2: Check function logic and typing
function describe(input: string | number): string { if (typeof input === 'string') return `String: ${input}`; else return `Number: ${input}`; } uses union type and checks input type to return correct description. Options C and D accept only one type, A uses any which loses type safety.Final Answer:
function describe(input: string | number): string { if (typeof input === 'string') return `String: ${input}`; else return `Number: ${input}`; } -> Option CQuick Check:
Union type with type check = function describe(input: string | number): string { if (typeof input === 'string') return `String: ${input}`; else return `Number: ${input}`; } [OK]
- Using any type losing safety
- Accepting only one type instead of both
- Not checking input type before returning
Ready to prove it?
Pass the test and this pattern moves unknown
