함수 타입 표현식Call SignatureConstruct SignaturesGeneric functionsOptional Parameters, Default parametersRest Parameters and Arguments(=python의 *)Rest ParametersRest ArgumentsParameter Destructuring ( 파라미터 구조 할당 )
함수 타입 표현식
function greeter(fn: (a: string) => void) { fn("Hello, World"); } function printToConsole(s: string) { console.log(s); } greeter(printToConsole);
- 함수를 표현하는 가장 간단한 방법은 함수 타입 표현식을 사용해서 가능함. 이 타입은 화살표 함수와 문법적으로 비슷함
Call Signature
- 자바스크립트에서는 함수가 호출가능한 것 이외에도 property를 가질 수 있는데 함수 타입 표현식으로는 해당 property를 명시할 수 없음
- 프로퍼티를 가진 호출가능한 함수를 서술하기 위해서는 call signature를 객체 타입으로 정의할 수 있음
type DescribableFunction = { description: string; (someArg: number): boolean; }; function doSomething(fn: DescribableFunction) { console.log(fn.description + " returned " + fn(6)); }
- 함수 표현식에서는
=>
를 사용했고, 여기서는:
를 사용함
Construct Signatures
- 자바스크립트 함수는
new
연산자와 함께 호출이 가능함
type SomeConstructor = { new (s: string): SomeObject; }; function fn(ctor: SomeConstructor) { return new ctor("hello"); }
Generic functions
function firstElement(arr: any[]) { return arr[0]; } // Generic 버전 function firstElement<Type>(arr: Type[]): Type | undefined { return arr[0]; }
Optional Parameters, Default parameters
function f(x?: number) { // ... } f(); // OK f(10); // OK function f(x = 10) { // ... } declare function f(x = 10): void; // cut // All OK f(); // x가 10으로 됨 f(10); f(undefined); // x가 10으로 됨
- optional parameter로 명시하기 위해
?
를 이용할 수도 있고default 값
을 설정할 수도 있음
Rest Parameters and Arguments(=python의 *)
Rest Parameters
function multiply(n: number, ...m: number[]) { return m.map((x) => n * x); } // 'a' gets value [10, 20, 30, 40] const a = multiply(10, 1, 2, 3, 4);
- 특정 파라미터 이후에 나타나는 파라미터 모두를 받고 싶을 때,
. . .
을 사용하기
Rest Arguments
- 배열을 풀어헤쳐서 배열 크기 만큼의 인자를 함수에 넘길 수 있음
const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; arr1.push(...arr2);
Parameter Destructuring ( 파라미터 구조 할당 )
function sum({ a, b, c }) { console.log(a + b + c); } sum({ a: 10, b: 3, c: 9 }); // 원래는 받아서 안에서 풀어야 할 것을 function sum(obj) { console.log(obj.a + obj.b + obj.c); }