functions-basic-syntax-and-types
1. Function Declaration Syntax:
TypeScript enhances JavaScript's function declaration by introducing type annotations for parameters and return types, providing benefits like early error detection and self-documenting code.
function greet(name: string): string {
return `Hello, ${name}!`;
}
2. Parameter Types:
By specifying types for function parameters, TypeScript helps to ensure that functions are called with the right type of arguments, leading to safer and more predictable code.
function add(x: number, y: number): number {
return x + y;
}
3. Return Types:
Declaring a return type in TypeScript function signatures guarantees that the function returns the expected type of value, reducing runtime errors and improving code clarity.
function getLength(s: string): number {
return s.length;
}
4. Optional Parameters:
Optional parameters in TypeScript are marked with a question mark and can be omitted when calling the function, providing flexibility while also enforcing types for provided arguments.
function buildName(firstName: string, lastName?: string): string {
if (lastName)
return firstName + " " + lastName;
else
return firstName;
}
5. Default Parameters:
Default parameter values in TypeScript not only prevent bugs by ensuring parameters are initialized but also implicitly define the type of the parameter.
function createGreeting(message: string, userName = "Anonymous"): string {
return `${message}, ${userName}!`;
}
6. Rest Parameters:
Rest parameters in TypeScript allow you to pass an indefinite number of arguments to a function. They're type-checked, ensuring that each argument matches the specified type.
function sumNumbers(...numbers: number[]): number {
return numbers.reduce((a, b) => a + b, 0);
}
7. Function Overloading:
With function overloading, TypeScript allows you to define multiple function signatures for a single implementation, providing type-checked flexibility in how a function can be called.
function makeDate(timestamp: number): Date;
function makeDate(m: number, d: number, y: number): Date;
function makeDate(mOrTimestamp: number, d?: number, y?: number): Date {
if (d !== undefined && y !== undefined) {
return new Date(y, mOrTimestamp, d);
} else {
return new Date(mOrTimestamp);
}
}
8. Void Return Type:
The void
return type in TypeScript clarifies that a function will not return any value, which can be useful for event handlers or functions that solely perform side effects.
function logMessage(message: string): void {
console.log(message);
}
9. Function Type Expressions:
Function type expressions in TypeScript describe the expected signature of functions, including parameter and return types, which is essential when passing functions as arguments.
let myFunction: (input: string) => number = function (str) {
return str.length;
};
10. this
Keyword Typing:
Typing the this
keyword in TypeScript function signatures can prevent bugs by ensuring the function is called with a specific this
context.
function handleClick(this: HTMLButtonElement) {
// 'this' is typed as HTMLButtonElement
console.log(this.textContent);
}
11. Callback Function Types:
Callback function types in TypeScript ensure that functions passed as arguments are called with the correct parameters and are expected to return a specific type.
function processData(callback: (data: string) => void) {
// Process some data and call the callback
callback('Processed Data');
}
12. Function Type Inference:
Type inference in TypeScript functions reduces the need for explicit type annotations, as the compiler can often deduce types from the context, making your code less verbose.
// The compiler infers the return type as 'number'
function add(x, y) {
return x + y;
}
13. Arrow Functions:
Arrow functions in TypeScript are concise and can include type information, which is useful for inline functions or functions that don’t need their own this
context.
const greet = (name: string): string => `Hello, ${name}!`;
14. Generics in Functions:
Generics in TypeScript functions allow for type parameters that ensure type safety for functions that operate on a variety of types without losing their specific type information.
function identity<T>(value: T): T {
return value;
}
15. never
Return Type:
The never
type for functions in TypeScript indicates that the function will never successfully complete its execution, which is useful for functions that throw errors or infinite loops.
function error(message: string): never {
throw new Error(message);
}
16. Function Signatures:
Function signatures in TypeScript define the expected parameter list and return type of a function, acting as a template for implementing the function in classes or other structures.
interface MathFunction {
(x: number, y: number): number;
}
let add: MathFunction = function (a, b) {
return a + b;
};
17. Type Assertions in Functions:
Type assertions in TypeScript functions allow you to override the inferred type and specify a more specific type, ensuring that you work with the correct type within the function.
function getLength(value: string | string[]) {
let len = (value as string[]).length;
// ...
}
18. Type Guards in Functions:
Type guards in TypeScript are expressions that perform a runtime check and narrow the type of a variable within a conditional block, ensuring type-specific operations can be performed safely.
function isString(test: any): test is string {
return typeof test === "string";
}
function example(foo: any) {
if (isString(foo)) {
console.log("It's a string!", foo.toUpperCase());
}
}
19. Async Functions and Promises:
Async functions in TypeScript automatically work with Promise
objects, and you can type the resolved value to ensure that the function's consumers can expect a specific value type.
async function fetchData(url: string): Promise<Data> {
let response = await fetch(url);
let data: Data = await response.json();
return data;
}
20. Constructor Functions:
Constructor functions in TypeScript can have their signature defined with types for both the constructor arguments and the type of the object they produce, aiding in object-oriented design.
type UserConstructor = new (name: string, age: number) => User;
function createUser(ctor: UserConstructor, name: string, age: number) {
return new ctor(name, age);
}