Typed functions in TypeScript
Parameter, return, and function-type annotations.
function greet(name: string, greeting = "Hello"): string {
return `${greeting}, ${name}!`;
}
const square = (x: number): number => x * x;
type Formatter = (value: number, digits?: number) => string;
const currency: Formatter = (value, digits = 2) =>
`$${value.toFixed(digits)}`;
function sum(...nums: number[]): number {
return nums.reduce((a, b) => a + b, 0);
}
How it works
- A default value makes a parameter optional.
- A
typealias can describe a whole signature. - Rest parameters type as an array.
Keywords and builtins used here
Formatterconstfunctionnumberreturnstringtype
The run, in numbers
- Lines
- 14
- Characters to type
- 366
- Tokens
- 113
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 71 seconds.
Step 1 of 5 in Functions & tuples, step 16 of 23 in Types & annotations.