# Typed Function Parameters — TypeScript

Source: https://www.geekswithgeeks.com/en/typescript/ts-function-basics

> Type parameters and return values, and make some optional.

## Params & return type

Annotate each parameter, and optionally the return type after `)`.

```typescript
function area(width: number, height: number): number {
  return width * height;
}
area(4, 5);   // 20
```

## Optional & default params

`?` marks a parameter optional; a default value makes it optional too and sets its type from that value.

```typescript
function greet(name: string, greeting: string = "Hello"): string {
  return `${greeting}, ${name}!`;
}
function findUser(id: number, cache?: Map<number, string>) { /* ... */ }
```

## Calling it wrong

Wrong argument count or type is rejected before the code ever runs.

```typescript
area(4);
// Error: Expected 2 arguments, but got 1.
area(4, "5");
// Error: Argument of type 'string' is not assignable to parameter of type 'number'.
```

**Quiz:** Which makes a function parameter optional?

- [x] A trailing `?` after its name
- [ ] Wrapping it in `unknown`
- [ ] Putting it first in the parameter list

*Answer:* A trailing `?` after its name. `name?: string` tells TS the caller may omit this argument.
