Last active
May 8, 2025 10:03
-
-
Save Elijah-trillionz/d77bcd807a96beca025b865d1898bf67 to your computer and use it in GitHub Desktop.
Code examples for article: "How to pass a TypeScript function"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// typescript pass-by-value | |
const numberIncrement = (a: number) => { | |
a = a + 1; | |
return a; | |
} | |
let a = 1; | |
let b = numberIncrement(a); | |
console.log(`pass by value -> a = ${a} b = ${b}`); | |
// typescript pass-by-reference | |
const arrayIncrement = (arr: number[]): void => { | |
arr.push(99); | |
}; | |
const originalArray: number[] = [1, 2, 3]; | |
arrayIncrement(originalArray); | |
console.log(`pass by ref => ${originalArray}`); | |
// typescript pass-by-reference: reassigning the reference | |
const arrayIncrement = (arr: number[]): void => { | |
arr = [...arr, 99]; | |
console.log(`arr inside the function => ${arr}`); | |
}; | |
//arr inside the function => 1,2,3,99 | |
const originalArray: number[] = [1, 2, 3]; | |
arrayIncrement(originalArray); | |
console.log(`arr outside => ${originalArray}`); | |
// typescript generics | |
function identity<T>(arg: T): T { | |
return arg; | |
} | |
console.log(identity("Hello, TypeScript!")); | |
console.log(identity(99)); | |
// typescript reusable & adaptable generics | |
function findElements<T>(arr: T[], filterFn: (item: T) => boolean): T[] { | |
return arr.filter(filterFn); | |
} | |
const arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; | |
const oddNumbers: number[] = findElements(arr, (num) => num % 2 === 1); | |
console.log("Odd Numbers:", oddNumbers); | |
interface Product { | |
name: string; | |
price: number; | |
} | |
const products: Product[] = [ | |
{ name: "Phone", price: 400 }, | |
{ name: "Laptop", price: 1000 }, | |
{ name: "Tablet", price: 300 } | |
]; | |
const cheapProducts = findElements(products, (p) => p.price < 500); | |
console.log('cheap products:', cheapProducts); | |
// typescript function overload | |
function greeting(input: string | string[]): string { | |
if (Array.isArray(input)) { | |
return input.map(greet => `Hello, ${greet}!`).join(' '); | |
} else { | |
return `Hello, ${input}!`; | |
} | |
} | |
// Consume the function | |
console.log(greeting('Bob')); | |
console.log(greeting(['Bob', 'Peter', 'Sam'])); | |
// typescript passing objects in functions | |
interface Product { | |
name: string; | |
price: number; | |
} | |
const getProductInfo = (product: Product): string => { | |
return `This is a ${product.name} made for durability and sustainability. Going for a whooping $${product.price}. Best offer!`; | |
}; | |
console.log(getProductInfo({ name: "Phone", price: 400 })) | |
// typescript optional properties | |
const getTotalDiscount = (purchasedProducts: Product[]): number => { | |
return purchasedProducts.reduce( | |
(total: number, p: Product) => (p.discount ? p.discount + total : total), // works fine | |
0 | |
); | |
}; | |
// typescript passing objects inline | |
const calculateShippingCost = (item: { | |
amount: number; | |
destination: { international: boolean }; | |
weight: number; | |
}): number => { | |
const baseRate = item.destination.international ? 25 : 5; | |
return item.weight * item.amount * baseRate; | |
}; | |
console.log(calculateShippingCost({ amount: 500, destination: { international: true }, weight: 30 })); | |
// typescript declaring type | |
interface User { | |
name: string; | |
age: number; | |
orders: number; | |
itemsInCart: number; | |
} | |
const greetUser = (user: User): string => { | |
return `Hello ${user.name}, you have ${user.itemsInCart} items in your cart!`; | |
}; | |
// typescript type data manipulation | |
type ApiResponse<T> = | |
| { status: "success"; data: T; timestamp: number } | |
| { status: "error"; error: string; code: number }; | |
const processResponse = (response: ApiResponse<User[]>): string => { | |
if (response.status === "success") { | |
// TypeScript knows this is the success branch | |
return `Got ${response.data.length} users`; | |
} else { | |
// TypeScript knows this is the error branch | |
return `Error ${response.code}: ${response.error}`; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment