Concept Flow - Parameter type annotations
Function Declaration
Parameters with Types
Function Call with Arguments
Type Checking
Function Runs
This flow shows how TypeScript checks parameter types during function calls before running the function.
function greet(name: string) { return `Hello, ${name}!`; } console.log(greet("Alice"));
| Step | Action | Parameter 'name' Type | Argument Passed | Type Check Result | Output |
|---|---|---|---|---|---|
| 1 | Function greet declared | string | N/A | N/A | N/A |
| 2 | Call greet with argument "Alice" | string | "Alice" | Matches string | N/A |
| 3 | Function body executes | string | "Alice" | N/A | "Hello, Alice!" |
| 4 | console.log outputs result | N/A | N/A | N/A | Hello, Alice! |
| Variable | Start | After Call | Final |
|---|---|---|---|
| name | undefined | "Alice" | "Alice" |
| return value | undefined | undefined | "Hello, Alice!" |
Parameter type annotations in TypeScript:
function funcName(param: type) { ... }
- Specify expected type after parameter name
- TypeScript checks argument types at call
- Errors occur if types don't match
- Helps catch bugs before running codeWhat does a parameter type annotation in TypeScript do?
Which of the following is the correct way to add a type annotation for a parameter named age that should be a number?
function checkAge(____) { return age > 18; }age: number.What will be the output of this TypeScript code?
function greet(name: string) { return `Hello, ${name}!`; }
console.log(greet(42));string parameter named name.42, which does not match the expected string type.Identify the error in this TypeScript function and choose the fix:
function multiply(x: number, y) { return x * y; }x has a type number, but y has no type annotation.y: y: number -> Option CYou want to write a function formatPrice that takes a price parameter which can be either a number or a string. How should you annotate the parameter to accept both types?
| between types.price: number | string to allow either type.| for multiple allowed types [OK]Pass the test and this pattern moves unknown