ํจ์์ ํ์ ๋ช ์
๐ typescript์์ ํจ์๋ฅผ ์์ฑํ๋ ๋ฐฉ๋ฒ์ ๋ํด ์์๋ณด์
1. ํจ์์ ๋ฐํ(return) ํ์
์ ์ง์ ํ๋ ๋ฐฉ๋ฒ
2. ์ ํ์ ๋งค๊ฐ๋ณ์(parameter)๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ๋ฒ
3. ๋งค๊ฐ๋ณ์์ ๋ํดํธ ๊ฐ์ ์ฃผ๋ ๋ฐฉ๋ฒ
1. ํจ์์ ๋ฐํ(return) ํ์ ์ ์ง์ ํ๋ ๋ฐฉ๋ฒ
syntax
function ํจ์์ด๋ฆ(๋งค๊ฐ๋ณ์1, ๋งค๊ฐ๋ณ์2) : ํจ์์ ๋ฐํํ์
{
}
โ๏ธ void ํ์
function test(): void {}
๐๐ป ์๋ฌด๊ฒ๋ ๋ฐํ ํ์ง ์๋ ํจ์์ ๋ฐํ ๊ฐ์ผ๋ก๋ง ์ฌ์ฉ๋ ์ ์๋ ํ์
string ํ์
function test(): string {
return "a";
}
๐๐ป string ๊ฐ์ผ๋ก return
string[] ํ์
function test(): string[] {
return ["a", "b"];
}
๐๐ป string ๋ฐฐ์ด ๊ฐ์ผ๋ก return
๐ number์ boolean๋ฑ ๋๋จธ์ง ํ์ ์๋ ๋์ผํ๊ฒ ์ ์ฉ๋๋ค.
2. ์ ํ์ ๋งค๊ฐ๋ณ์(parameter)๋ฅผ ์ ๋ฌํ๋ ๋ฐฉ๋ฒ
- ๋ค์๊ณผ ๊ฐ์ ํจ์๊ฐ ์๋ค๊ณ ๊ฐ์ ํด๋ณด์
function test(a: string, b: string): void {
console.log(a, b);
}
test("hi", "yelim");
๐ ๋ง์ฝ ์ฌ๊ธฐ์ ์ธ์(argment)๊ฐ์ ํ๋๋ง ์ ๋ฌํ๋ค๊ณ ํ๋ฉด error๊ฐ ๋ฐ์ํ ๊ฒ์ด๋ค.

โ ์ ๊ทธ๋ฐ๊ฒ์ผ๊น ?
ํ์
์คํฌ๋ฆฝํธ๋ ํจ์์ ์ ์๋ ๋ชจ๋ ๋งค๊ฐ๋ณ์๊ฐ ํจ์์ ํ์ํ๋ค๊ณ ๊ฐ์ ํ๊ธฐ ๋๋ฌธ์ด๋ค.
-> ํจ์ ํธ์ถ์ ํ์
์คํฌ๋ฆฝํธ ์ปดํ์ผ๋ฌ๋ parameter ์ argument๋ฅผ ๋น๊ต ๊ฒ์ฌํ๊ฒ ๋๋ค.
๐ง ์ด๋ป๊ฒ ํด๊ฒฐํ ์ ์์๊น?
์ด์ ์ ํ์
๋ช
์์ ๊ฐ์ด ์์ด๋ ๋๊ณ ์์ด๋ ๋๋ ๊ฐ !
์ ํ์ ๋งค๊ฐ๋ณ์(optional parameter)๋ฅผ ์ฌ์ฉํ์ฌ ํด๊ฒฐํด๋ณด์
function test(a: string, b?: string): void {
console.log(a, b);
}
test("hi");
โ๏ธ ์ฌ๊ธฐ์ ์ฃผ์์ฌํญ
๋ง์ฝ ์ ๋ฌ๋๋ ๋งค๊ฐ๋ณ์๊ฐ ์ฌ๋ฌ๊ฐ์ด๊ณ ,
๋ช๊ฐ์ง๋ง ์ ํ์ ๋งค๊ฐ๋ณ์์ธ ๊ฒฝ์ฐ ??
๐๐ป ์ ํ์ ๋งค๊ฐ๋ณ์๋ค์ ๋ฐ๋์ ! ํ์ ๋งค๊ฐ๋ณ์ ๋ค์ ์์นํด์ผํ๋ค !
function test(a: string, b?: string, c?: string, d?: string, e?: string): void {
console.log(a, b, c, d, e);
}
test("hi");
- ์ปดํ์ผ ์์ผ์ console๋ก ์ดํด๋ณด๊ฒ ๋๋ฉด ๋ค์๊ณผ ๊ฐ์ด ํ ๋น๋์ง ์์ argument๊ฐ์ parameter๋ก ์ ๋ฌ๋์ง ์์ undefined๋ก ํ์๋๋ค.
hi undefined
๐๐ป ์ด๋ด๋ ํ ๋น๋ ๊ธฐ๋ณธ๊ฐ์ ์ฌ์ฉํ ์ ์๋ค ? ๋ฐ๋ก
3. ๊ธฐ๋ณธ ๋งค๊ฐ ๋ณ์(Default Parameter)
function test(a: string, b = 'yelim'): void {
console.log(a, b);
}
test("hi");
๐ ๊ทธ๋ฅ parmeter ๋ค์ ๊ฐ์ ์ค์ ํด์ฃผ๋ฉด ๋๋ค.
๐ ๋งค๊ฐ๋ณ์๋ค์ ๊ฐ์ ์ค์ ํด ์ฃผ๋ฉด๋๋ค.(์ ํ์ ํ๊ธฐ(?), ํ์
์๋ต๊ฐ๋ฅ -> ํ์
์ถ๋ก ์ผ๋ก ์ปค๋ฒ๊ฐ๋ฅ)
๐๐ป ๋ค์๊ณผ ๊ฐ์ ์ฝ๋์์ ๋ฌด์์ด ์ถ๋ ฅ๋ ์ง ์๊ฐํด๋ณด์ !
function test(a = 'hello', b = 'yelim'): void {
console.log(a, b);
}
test();
test('hi');
test('hi','there');
// 1. ๐ hello yelim
// 2. ๐ hi yelim
// 3. ๐ hi there
(์ฐธ๊ณ ์์) ๋ ์ฝฉ์ฝ๋ฉ : https://www.youtube.com/watch?v=SVtqhpboxGw&t=2s