문장(statement)과 표현식(expressoin)

Changhan·2025년 1월 26일

Typescript

목록 보기
13/29

이 두 개념은 아직 잘 모르지만, 함수의 선언 방식에는 두 가지가 있다는 것은 알고 있다.

// 문장 (statement)
function add(x: number, y: number): number {
  return x + y;
}

// 표현식 (expression)
const addd = (x: number, y: number) => {
  return x + y;
};

두 방식의 차이는?

함수의 시그니쳐는 같은데 다른 기능을 함수들이 있다고 가정해보자.

// statement
function subtract(x: number, y: number): number {
  return x - y;
}
function multipy(x: number, y: number): number {
  return x * y;
}
function divide(x: number, y: number): number {
  return x / y;
}

statement의 경우는 함수의 매개변수 각각에 타입을 지정해줘야 한다.

// expression
type CalculatorTyoe = (x: number, y: number) => number;

const add2: CalculatorTyoe = (x, y) => {
  return x + y;
};
const subtract2: CalculatorTyoe = (x, y) => {
  return x - y;
};
const multiply2: CalculatorTyoe = (x, y) => {
  return x * y;
};
const divide2: CalculatorTyoe = (x, y) => {
  return x / y;
};

expression은 할당을 활용해서 각각의 변수에 해당 타입을 넣어주면 된다. 확실히 expression 방식이 코드가 더 깔끔하고, 정돈되어 보인다.

0개의 댓글