나머지 매개변수

함수 호출 시 전달되는 나머지 인수를 배열 형태로 수집하는데 사용

// 기본 문법
function 함수이름(필수매개변수: 타입, ...나머지매개변수: 타입[]) {
   return
}

 

// 1. 숫자 합산 함수
function sum(...numbers: number[]): number {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // 출력: 10
console.log(sum()); // 출력: 0

// 2. 문자열 연결 함수
function concatenate(separator: string, ...strings: string[]): string {
  return strings.join(separator);
}

console.log(concatenate(", ", "apple", "banana", "cherry")); // 출력: "apple, banana, cherry"
console.log(concatenate(" - ", "React", "TypeScript")); // 출력: "React - TypeScript"

// 3. 혼합된 매개변수 처리
function greet(greeting: string, ...names: string[]): void {
  names.forEach((name) => {
    console.log(`${greeting}, ${name}!`);
  });
}

greet("Hello", "Alice", "Bob", "Charlie");
// 출력:
// Hello, Alice!
// Hello, Bob!
// Hello, Charlie!

this

this는 함수가 호출된 컨텍스트(문맥)에 따라 값이 결정 

// this 기본 동작
class Person1 {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet() {
    console.log(`Hello, my name is ${this.name}.`);
  }
}

const person1 = new Person1("Alice");
person1.greet(); // "Hello, my name is Alice."

 

// 화살표 함수와 this
// 화살표 함수는 렉시컬 바인딩 사용
// * 렉시컬 바인딩은 프로그래밍 언어에서 변수의 스코프가 변수 선언 위치에 따라 결정되고, 코드가 작성된 구조에 따라 바인딩되는 방식
// this는 화살표 함수가 선언된 위치에서의 this 값을 그대로 유지
class Person {
  name: string;

  constructor(name: string) {
    this.name = name;
  }

  greet1 = () => {
    console.log(`Hello, my name is ${this.name}.`);
  };
}

const person = new Person("Alice");
const unboundGreet = person.greet1;
unboundGreet(); // "Hello, my name is Alice."

// 타입스크립트에서 this 명시
function showInfo(this: { name: string; age: number }) {
  console.log(`Name: ${this.name}, Age: ${this.age}`);
}

const userInfo = { name: "Bob", age: 30 };

// call을 통해 this 바인딩
showInfo.call(userInfo); // 출력: "Name: Bob, Age: 30"

// showInfo(); // 오류: 'this'가 명시된 타입에 맞지 않음

 

// 화살표 함수와 일반 함수의 혼합 사용
class Button {
  label: string;

  constructor(label: string) {
    this.label = label;
  }

  handleClick = () => {
    console.log(`Button clicked: ${this.label}`);
  };
}

const button = new Button("Submit");
const callback = button.handleClick;
callback(); // "Button clicked: Submit"

함수 오버로드

동일한 함수 이름을 사용하지만, 다양한 인수 목록이나 반환 타입을 허용하는 기능

/ 오버로드 시그니처 선언

function add2(x: number, y: number): number;
function add2(x: string, y: string): string;

// 2. 실제 구현
function add2(x: any, y: any): any {
    return x + y;
}

// 사용 예제
let sum2 = add2(10, 20); // 결과는 숫자 30
let concatenation = add2("Hello", "World"); // 결과는 문자열 "HelloWorld"

console.log(sum2); // 출력: 30
console.log(concatenation); // 출력: HelloWorld

 

'TS' 카테고리의 다른 글

교차 타입  (0) 2024.11.29
리터럴 타입  (0) 2024.11.26
함수(Function)[1]  (0) 2024.11.20
Interface(3)  (0) 2024.11.19
Interface (2)  (0) 2024.11.18

+ Recent posts