Home >Web Front-end >JS Tutorial >Mastering TypeScript Functions: Your Guide to Stronger, Safer Code
function greet(name: string): string { return `Hello, ${name}!`; }
This function takes a string parameter and guarantees a string return value.
const multiply = (a: number, b: number): number => a * b;
Here, we define a function that takes two numbers and returns their product.
function createUser(name: string, age?: number, role: string = 'user') { // Implementation }
In this example, 'age' is optional, and 'role' has a default value of 'user'.
function sum(...numbers: number[]): number { return numbers.reduce((total, num) => total + num, 0); }
This function can take any number of numeric arguments and return their sum.
function processInput(input: string): string; function processInput(input: number): number; function processInput(input: string | number): string | number { if (typeof input === 'string') { return input.toUpperCase(); } else { return input * 2; } }
This function can handle both string and number inputs, with different behavior for each.
function firstElement<T>(arr: T[]): T | undefined { return arr[0]; }
This generic function can work with arrays of any type and return the first element of that type.
TypeScript functions provide a robust foundation for building complex applications. By leveraging these features, you can write more expressive, safer, and self-documenting code.
Remember: The goal is not just to add types, but to use TypeScript's features to create more reliable and maintainable code structures.
I hope you learned something new in this short blog. :)
The above is the detailed content of Mastering TypeScript Functions: Your Guide to Stronger, Safer Code. For more information, please follow other related articles on the PHP Chinese website!