πŸ†Β λͺ©ν‘œ

ν•¨μˆ˜ μ„ μ–Έκ³Ό 호좜

일반적으둜 νƒ€μž…μŠ€ν¬λ¦½νŠΈμ—μ„œ ν•¨μˆ˜μ˜ ν˜ΈμΆœμ€ λ‹€μŒκ³Ό 같이 ν•œλ‹€.

function add(a: number, b: number) {
	return a + b;
}

μ—¬λŸ¬κ°€μ§€μ˜ ν•¨μˆ˜ 선언방식

function greet(name: string) {
	return "hello" + name;
}

const greet = function(name: string) {
	return "hello" + name;
}

const greet = (name: string) => {
	return "hello" + name;
}

const greet = (name: string => "hello" + name;

const greet = new Function('name', 'return "hello" + name');

λ§ˆμ§€λ§‰ 방법은 μ‚¬μš©ν•˜μ§€ μ•ŠλŠ”λ‹€.

ν•¨μˆ˜ 선언을 톡해 μ„ μ–Έλœ ν•¨μˆ˜λ₯Ό ν˜ΈμΆœν•˜κ²Œ 되면 λ§€κ°œλ³€μˆ˜μ˜ νƒ€μž…μ²΄ν¬λ₯Ό 톡해 호좜 κ°€λŠ₯ν•œμ§€λ₯Ό ν™•μΈν•˜μ—¬ ν•„μš”μ— 따라 μ—λŸ¬λ₯Ό λ°œμƒμ‹œν‚¨λ‹€.

선택적 λ§€κ°œλ³€μˆ˜μ™€ κΈ°λ³Έ λ§€κ°œλ³€μˆ˜

// 선택적 λ§€κ°œλ³€μˆ˜
function log(message: string, userId?: string) {
	console.log(message, userId || 'Not signed in');
}

// κΈ°λ³Έ λ§€κ°œλ³€μˆ˜
function log(message: string, userId = 'Not signed in') {
	console.log(message, userId);
}

일반적으둜 선택적 λ§€κ°œλ³€μˆ˜λ³΄λ‹€ κΈ°λ³Έ λ§€κ°œλ³€μˆ˜λ₯Ό μ‚¬μš©ν•˜λŠ” 것이 더 λ§Žμ€ 일을 ν•˜κΈ° λ•Œλ¬Έμ— 자주 μ‚¬μš©ν•˜κ²Œ λœλ‹€.

λ‚˜λ¨Έμ§€ λ§€κ°œλ³€μˆ˜

κ°€λ³€ 인자λ₯Ό λ°›λŠ” μƒν™©μ—μ„œ μ‚¬μš©ν•˜λ©΄ μ’‹λ‹€.

function sum(...numbers: number[]) {
	return numbers.reduce((total, n) => total + n, 0);
}