-
ν¨μμ νμ λͺ μβ¨οΈ conceptualization/Typescript 2022. 9. 11. 18:37728x90
π 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
'β¨οΈ conceptualization > Typescript' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
μ νΈλ¦¬ν° νμ (Utilty Types) (0) 2022.09.12 Generics μ λνμ¬ (0) 2022.09.12 Any, Union Type, Intersection Type, Type Aliases & Type Guardsμ λν΄μ μμ보기 (0) 2022.09.11 μ΄κ±°ν(Enum) κ³Ό 리ν°λ΄ νμ (0) 2022.09.11 νμ μΌλ‘ μ¬μ©λλ μΈν°νμ΄μ€ (Interface) (0) 2022.09.09