TypeScript
/Beginner
Function Types
Definition
Defining the specific types of arguments a function accepts, as well as the exact type of data it returns.
Explain Like I'm New
A function is a factory machine. A Function Type is the label on the machine that says: 'Insert exactly 2 Blocks of Wood (Arguments) here. Out of the other side will come exactly 1 Wooden Chair (Return Type). Do not insert Metal.'
Real World Example
Typing a callback function passed as a React prop: `onDelete: (id: string) => void`.
Common Use Cases
- •Ensuring correct parameters are passed
- •Defining React component props
- •Higher-order functions
Interactive Example
// 1. Typing the function declaration directly function calculateArea(width: number, height: number): number { return width * height; } // 2. Typing an arrow function const greet = (name: string): string => { return `Hello ${name}`; }; // 3. Defining a standalone Function Type Signature (Useful for props!) type MathOperation = (a: number, b: number) => number; const add: MathOperation = (x, y) => x + y; const subtract: MathOperation = (x, y) => x - y; // ERROR: Type 'string' is not assignable to type 'number' // const badMath: MathOperation = (x, y) => "hello";
Interview Questions
basic
- How do you type a function that doesn't return anything?
intermediate
- What is the difference between `(a: number) => void` and `Function`?
advanced
- What is the difference between `void` and `never` as a return type?